Tomcat 是个Java应用程序, 作为一个Web容器, 带有请求/响应的HTTP服务器
Web容器
创建Servlet实例, 完成Servlet名称注册和URL模式对应, Web容器转发给Servlet处理,
请求过来时 创建HttpServletRequest 和 HttpServletResponse 对象, 请求结束时销毁,
Servlet
生命周期重要的3个方法, init() service() destory()
Serlvet ServletConfig GenericServlet, 3个类的关系, GenericServlet 类会把默认的配置init(ServletConfig servletConfig) 放入Servlet中
ServletContext 在整个Web应用程序加载容器完成之后会创建一个全局的ServletContext 对象 代表整个英雄程序, 可通过ServletConfig获取
监听器
ServletRequestListener , HttpSessionListener, ServletConttextListener
Session的属性变化监听,移除监听,
过滤器
请求的编码格式过滤
请求封装器, 在请求过来时替换<>这些防止xss攻击,SQL注入
package com.example.demo.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.IOException; @WebFilter public class EscapeFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("EscapeFilter doFilter"); HttpServletRequestWrapper requestWrapper = new EscapeWrapper((HttpServletRequest) request); chain.doFilter(requestWrapper, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("EscapeFilter init"); } @Override public void destroy() { System.out.println("EscapeFilter destroy"); } }
Wrapper
package com.example.demo.filter; import org.apache.commons.lang3.StringEscapeUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class EscapeWrapper extends HttpServletRequestWrapper { public EscapeWrapper(HttpServletRequest request) { super(request); } @Override public String getParameter(String name) { String value = getRequest().getParameter(name); return StringEscapeUtils.escapeHtml4(value); //return super.getParameter(name); } }
响应封装器, 同请求封装器,大同小异