请求Servlet的时候带一个参数,该参数决定要执行Servlet中的方法(以get方法为例)
@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//重写service方法
@Override
public void service(HttpServletRequest request, HttpServletResponse response) {
String param = request.getParameter("method");
if(param!=null) {
try {
Method method = this.getClass().getMethod(param, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, request,response);
}catch(Exception e) {
e.printStackTrace();
}
}
}
//测试方法
public void test(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("调用了此方法");
}
}
测试:
image.png
结果:
image.png
网友评论