servlet模拟SpringMVC
2021-05-15 15:29
标签:style extends ppi private doget isp print coding XML 1. web.xml 2. DispatcherServlet.java 3. HttpServletHandler.java(接口) 4. AddUserHandler.java(处理器handler) servlet模拟SpringMVC 标签:style extends ppi private doget isp print coding XML 原文地址:https://www.cnblogs.com/amiezhang/p/9750697.htmlxml 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>DispatcherServletservlet-name>
servlet-class>amie.servlet.DispatcherServletservlet-class>
load-on-startup>2load-on-startup>
servlet>
servlet-mapping>
servlet-name>DispatcherServletservlet-name>
url-pattern>/url-pattern>
servlet-mapping>
web-app>
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();
}
}
}
public interface HttpServletHandler {
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
/***
* 处理器:专门处理不同业务请求的
*/
public class AddUserHandler implements HttpServletHandler{
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 设置响应体的媒体类型
response.setContentType("text/plain;charset=utf-8");
// 响应
response.getWriter().print("添加成功");
}
}
下一篇:python编程
文章标题:servlet模拟SpringMVC
文章链接:http://soscw.com/index.php/essay/85846.html