使用方式
在访问服务器的时候在后面带上?methon=方法名 即可调用方法
比如访问TestServlet?method=regist 就会调用下面的方法
1 2 3 4 5 6 7 8 9 10 11 12
| @WebServlet("/TestServlet") public class TestServlet extends BaseServlet {
public String regist(HttpServletRequest request, HttpServletResponse response){ try { response.sendRedirect("https://www.baidu.com"); } catch (IOException e) { e.printStackTrace(); } return null; } }
|
BaseServlet 源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class BaseServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); String methodName = request.getParameter("method");
Method method = null;
try { method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); } catch (Exception var10) { throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", var10); } String result = null;
try {
result = (String)method.invoke(this, request, response); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }
if (result != null && !result.trim().isEmpty()) { int index = result.indexOf(":"); if (index == -1) { request.getRequestDispatcher(result).forward(request, response); } else { String start = result.substring(0, index); String path = result.substring(index + 1); if (start.equals("f")) { request.getRequestDispatcher(path).forward(request, response); } else if (start.equals("r")) { response.sendRedirect(request.getContextPath() + path);
} } } }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
|