1、编写baseController
2、子类继承baseController
前端需要每次传入action表示需要执行controller中的方法
baseController
package com.cn.fb.controller;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class baseController extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 设置请求响应的字符集编码格式 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); // 前端传入需要执行的方法名参数 String action = request.getParameter("action"); // 获取类对象 Class clazz = this.getClass(); // 通过反射获取方法 Method declaredMethod = clazz.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // 执行方法并且获取返回值 Object object = declaredMethod.invoke(this, request, response); // 判断返回值 if (object != null && object instanceof String) { String url = (String) object; if (url.startsWith("f:")) { // 请求转发 request.getRequestDispatcher(url.substring(2)).forward(request, response); } else if (url.startsWith("r:")) { // 重定向 response.sendRedirect(url.substring(2)); } else { // 返回字符串或JSON到浏览器 PrintWriter writer = response.getWriter(); writer.print(url); writer.flush(); writer.close(); } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }}
子类
package com.cn.fb.controller;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet(value = "/user")public class UserController extends baseController { public String selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return "f:list.jsp"; }}