
<a href="customerServlet?method=add">Add</a>
<br><br>
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>zzuli.mvcapp.servlet.CustomerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/customerServlet</url-pattern>
</servlet-mapping>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
switch(method) {
case "add" : add(request,response);break;
case "query" : query(request,response);break;
case "delete" : delete(request,response);break;
}
}



利用反射实现多个请求访问一个Servlet
<a href="addCustomer.do">Add</a>
<br><br>
<a href="deleteCustomer.do">Delete</a>
<br><br>
映射为*.do,
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>zzuli.mvcapp.servlet.CustomerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取servletPath:/add.do
String servletPath = request.getServletPath();
String methodName = servletPath.substring(1);
//得到方法名,去掉:/ .do
methodName = methodName.substring(0, methodName.length() - 3);
try {
//利用反射获取method对应的方法
Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//利用反射调用对应的方法
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}

拼SQL语句
@Override
public List<Customer> getForListWithCriteriaCustomer(CriteriaCustomer cc) {
String sql = "SELECT * FROM customer WHERE name LIKE ? AND address LIKE ? "
+"AND phone LIKE ?";
//在CriteriaCustomer里边封装了geter,seter方法,得到"%%","%name"
return getForList(sql, cc.getName(), cc.getAddress(), cc.getPhone());
}
public String getAddress() {
if(address == null)
address = "%%";
else
address = "%" + address + "%";
return address;
}







1170

被折叠的 条评论
为什么被折叠?



