servlet模拟SpringMVC
1. web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="3.1"> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>amie.servlet.DispatcherServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <!-- servlet拦截下所有请求,交给DispatchServlet处理 --> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2. DispatcherServlet.java
public class DispatcherServlet extends HttpServlet { private static final long serialVersionUID = 116714888769576151L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 获取请求URI String requestURI = request.getRequestURI(); // 请求分发,根据不同请求URL,调用不同的业务处理器 // 注意事项:一个处理器handler类,只有一个方法 // 这个分发逻辑需要好好设计一下 Object handler = null; // 首先根据请求URL,查找到对应的处理器 if ("/queryUser".equals(requestURI)) { handler = new QueryUserHandler(); } else if ("/addUser".equals(requestURI)) { handler = new AddUserHandler(); } if (handler == null) { // 设置响应体的媒体类型 response.setContentType("text/plain;charset=utf-8"); // 响应 response.getWriter().print("请求找不到"); return; } // 其次再去调用对应处理器的方法 if (handler instanceof QueryUserHandler) { ((QueryUserHandler) handler).handleRequest(request, response); }else if (handler instanceof AddUserHandler) { ((AddUserHandler) handler).handleRequest(request, response); } // 处理结果 } catch (Exception e) { e.printStackTrace(); } } }
3. HttpServletHandler.java(接口)
public interface HttpServletHandler { public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception; }
4. AddUserHandler.java(处理器handler)
/*** * 处理器:专门处理不同业务请求的 */ public class AddUserHandler implements HttpServletHandler{ public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { // 设置响应体的媒体类型 response.setContentType("text/plain;charset=utf-8"); // 响应 response.getWriter().print("添加成功"); } }