您的位置:首页 > 编程语言 > Java开发

JAVAWEB-MVC案例分析-Servlet实现(2)

2018-01-10 11:23 381 查看
继续以前的MVC案例分析,今天写第2部分。

一、第一种实现方法



(1)test.jsp主体代码

<a href="customerServlet?method=add">Add</a>
<br><br>
<a href="customerServlet?method=query">Query</a>
<br><br>
<a href="customerServlet?method=delete">Delete</a>
<br><br>
<a href="customerServlet?method=update">Update</a>
<br><br>

(2)CustomerServlet.java主体代码

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;
case "update": update(request,response);break;
}二、第二种实现方法



(1)test.jsp主体代码

<a href="add.do">Add</a>
<br><br>
<a href="query.do">Query</a>
<br><br>
<a href="delete.do">Delete</a>
<br><br>
<a href="edit.do">Edit</a>
<br><br>
(2)CustomerServlet.java
//1、获取ServletPath:/edit.do或/add.do
String servletPath = request.getServletPath();
//System.out.println(servletPath);
//2、去除/和.do,得到类似于edit或add这样的字符串
String methodName = servletPath.substring(1);
methodName = methodName.substring(0, methodName.length()-3);
//System.out.println(methodName);

//调用对应的方法
Method method = null;
try {
//3、利用反射获取methodName对应的方法
method = getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//利用反射调用对应的方法
method.invoke(this, request,response);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVAWEB Servlet MVC案例
相关文章推荐