Simply MVC FrameWork

使用反射简单模拟MVC对请求的处理过程

使用反射简单模拟MVC对请求的处理过程

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        String path = req.getServletPath();
        System.out.println("path:"+path);
        String className = path.substring(1, path.lastIndexOf("/"));
        String methodName = path.substring(path.lastIndexOf("/") + 1);

        System.out.println("className:"+className);
        System.out.println("methodName:"+methodName);
        Class clazz = null;
        Object controller = null;
        try {
            clazz = Class.forName("Controller." + className);
            System.out.println("创建controller对象:"+"controller."+className);
            controller = clazz.newInstance();
            Method method = clazz.getMethod(methodName, new  Class[] {HttpServletRequest.class});
            Object result = method.invoke(controller, new  Object[]{req});
            System.out.println("//调用controller中的方法:"+methodName);
            ObjectMapper om = new ObjectMapper();
            PrintWriter writer = resp.getWriter();
            writer.print(om.writeValueAsString(result));
            System.out.println("//执行结果:"+om.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}