这样写有一定的好处,当提交的method无需再进行判断,例如有100个方法就没必要进行判断了直接可以用映射的方式直接找到method所要运用的方法
(1)构建一个BasicServlet来继承Servlet对象
public class BasicServlet extends HttpServlet{
@Override
public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException {
}
}
(2)获得method所要调用的方法的string类型,例如“save”,“update”
如果为空的话就是默认的方法例如:listUI
(3):获得正在执行的Servlet的字节码
(4)获得正在执行的指定的方法
public class BasicServlet extends HttpServlet{
@Override
public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException {
String MethodName=req.getParameter("method");
//1.如果方法名为空的话就默认是listui方法,读者可自行更改
if(MethodName==null) {
MethodName="listUI";
}
//2.获得正在执行的Servlet的字节码
Class clazz=this.getClass();
try {
//3.获得正在执行的指定的方法
Method method= clazz.getDeclaredMethod(MethodName, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后就大功告成了(骗你的)
(5)写一个UserAction来继承BasicServlet方法,可以在这写你所需要的100种方法,无需再判断,指定路径是“UserAction.action”,命名随你啦
@WebServlet("/UserAction.action")
public class UserAction extends BasicServlet{
//默认方法
public void listUI(HttpServletRequest req,HttpServletResponse resp) throws ServletException {
System.out.println("查询");
}
public void save(HttpServletRequest req,HttpServletResponse resp) throws ServletException {
System.out.println("保存");
}
public void update(HttpServletRequest req,HttpServletResponse resp) throws ServletException {
System.out.println("更新");
}
}