在web容器调用Servlet的service()方法之前,Servlet并不知道请求的到来,就有了一段“请求到来空白期间”;而在调用Servlet的service()之后,web容器真正对浏览器响应之前,浏览器也并不知道真正的Servlet的响应,就有了一段“响应到达空白期间”。过滤器的作用就是在两段空白期间对请求和响应对象进行操作
public interface Filter {
void init(FilterConfig var1) throws ServletException;
void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;
void destroy();
}
过滤器也有自身的生命周期方法和Servlet极其的相似,每一个Filter都会有一个对应的FilterConfig,定义获取初始化参数的方法
public interface FilterConfig {
String getFilterName();
ServletContext getServletContext();
String getInitParameter(String var1);
Enumeration<String> getInitParameterNames();
}
真正做过滤处理的方法就是doFilter(),如果调用了FilterChain的doFilter()方法,就会运行下一个过滤器,如果没有下一个过滤器,就调用请求目标Servlet的service()方法;不过因为某种情况(用户验证不过关),就不会调用FilterChain的doFilter(),当然之后请求也不会交给相应的Servlet来处理了
public interface FilterChain {
void doFilter(ServletRequest var1, ServletResponse var2) throws IOException, ServletException;
}
@WebFilter(filterName = "DIYFilter", urlPatterns = "/*",
initParams = {
@WebInitParam(name = "filter-key", value = "filter-val")
},
dispatcherTypes = {
DispatcherType.FORWARD,
DispatcherType.INCLUDE,
DispatcherType.ERROR,
DispatcherType.ASYNC,
DispatcherType.REQUEST
})
public class DIYFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
// 获取请求开始时间,用于计算一次请求到响应的耗时情况
long begin = System.currentTimeMillis();
chain.doFilter(req, resp);
// 响应时间
long end = System.currentTimeMillis();
System.out.print("请求处理时间:" + (end - begin));
}
public void init(FilterConfig config) throws ServletException {
}
}
过滤器可以定义初始化参数;一般过滤器过滤的请求都是由浏览器直接发出的,对于请求转发的Servlet则需要配置DispatcherType,上诉配置信息也可以在web.xml中进行配置:
<filter>
<filter-name>DIYFilter</filter-name>
<filter-class>DIYFilter</filter-class>
<!-- 配置过滤器初始化参数 -->
<init-param>
<param-name>filter-key</param-name>
<param-value>filter-val</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DIYFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- 配置通过请求转发等其他方式也会被过滤的dispatcher -->
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping>
如果有多个过滤器,则会根据在web.xml中出现的先后顺序决定过滤器的运行顺序
请求装饰器HttpServletRequestWrapper
HttpServletRequest可以通过getParameter()获取到客户提交的请求参数,却没有setParameter()方法来修改请求参数,所幸有个HttpServletRequestWrapper来帮助我们来实现这一功能
public class HttpServletRequestWrapper extends ServletRequestWrapper implements HttpServletRequest {
public HttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
private HttpServletRequest _getHttpServletRequest() {
return (HttpServletRequest)super.getRequest();
}
public String getAuthType() {
return this._getHttpServletRequest().getAuthType();
}
public Cookie[] getCookies() {
return this._getHttpServletRequest().getCookies();
}
public long getDateHeader(String name) {
return this._getHttpServletRequest().getDateHeader(name);
}
public String getHeader(String name) {
return this._getHttpServletRequest().getHeader(name);
}
public Enumeration<String> getHeaders(String name) {
return this._getHttpServletRequest().getHeaders(name);
}
public Enumeration<String> getHeaderNames() {
return this._getHttpServletRequest().getHeaderNames();
}
public int getIntHeader(String name) {
return this._getHttpServletRequest().getIntHeader(name);
}
public String getMethod() {
return this._getHttpServletRequest().getMethod();
}
public String getPathInfo() {
return this._getHttpServletRequest().getPathInfo();
}
public String getPathTranslated() {
return this._getHttpServletRequest().getPathTranslated();
}
public String getContextPath() {
return this._getHttpServletRequest().getContextPath();
}
public String getQueryString() {
return this._getHttpServletRequest().getQueryString();
}
public String getRemoteUser() {
return this._getHttpServletRequest().getRemoteUser();
}
public boolean isUserInRole(String role) {
return this._getHttpServletRequest().isUserInRole(role);
}
public Principal getUserPrincipal() {
return this._getHttpServletRequest().getUserPrincipal();
}
public String getRequestedSessionId() {
return this._getHttpServletRequest().getRequestedSessionId();
}
public String getRequestURI() {
return this._getHttpServletRequest().getRequestURI();
}
public StringBuffer getRequestURL() {
return this._getHttpServletRequest().getRequestURL();
}
public String getServletPath() {
return this._getHttpServletRequest().getServletPath();
}
public HttpSession getSession(boolean create) {
return this._getHttpServletRequest().getSession(create);
}
public HttpSession getSession() {
return this._getHttpServletRequest().getSession();
}
public String changeSessionId() {
return this._getHttpServletRequest().changeSessionId();
}
public boolean isRequestedSessionIdValid() {
return this._getHttpServletRequest().isRequestedSessionIdValid();
}
public boolean isRequestedSessionIdFromCookie() {
return this._getHttpServletRequest().isRequestedSessionIdFromCookie();
}
public boolean isRequestedSessionIdFromURL() {
return this._getHttpServletRequest().isRequestedSessionIdFromURL();
}
/** @deprecated */
public boolean isRequestedSessionIdFromUrl() {
return this._getHttpServletRequest().isRequestedSessionIdFromUrl();
}
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
return this._getHttpServletRequest().authenticate(response);
}
public void login(String username, String password) throws ServletException {
this._getHttpServletRequest().login(username, password);
}
public void logout() throws ServletException {
this._getHttpServletRequest().logout();
}
public Collection<Part> getParts() throws IOException, ServletException {
return this._getHttpServletRequest().getParts();
}
public Part getPart(String name) throws IOException, ServletException {
return this._getHttpServletRequest().getPart(name);
}
public <T extends HttpUpgradeHandler> T upgrade(Class<T> httpUpgradeHandlerClass) throws IOException, ServletException {
return this._getHttpServletRequest().upgrade(httpUpgradeHandlerClass);
}
}
/**
* HttpServletRequest包装类,用于处理请求中的参数
*/
public class DIYRequestWrapper extends HttpServletRequestWrapper {
public DIYRequestWrapper(HttpServletRequest request) {
super(request);
}
public String getParameter(String name) {
String oldPara = getRequest().getParameter(name);
// 当请求参数中包含><等字符,将其转义为><;防止脚本注入
String newPara = oldPara.replace("<","<").replace(">",">");
return newPara;
}
}
然后将该Wrapper类用于过滤器中,这样子每次请求中的请求参数都能被Wrapper中定义的处理机制处理
@WebFilter("/*")
public class RequestWrapperFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
// 在过滤器中,通过requestWrapper类来处理请求参数
HttpServletRequest reqWrp = new DIYRequestWrapper((HttpServletRequest) req);
HttpServletResponse response = (HttpServletResponse)resp;
// 解决中文字符以 锛氱幇鍦 的乱码格式
response.setHeader("Content-type", "text/html;charset=UTF-8");
// 解决中文字符以 ???? 的乱码格式
response.setCharacterEncoding("utf-8");
chain.doFilter(reqWrp, response);
}
public void init(FilterConfig config) throws ServletException {
}
}
响应装饰器HttpServletResponseWrapper
若要对浏览器进行输出响应,必须通过getWriter()获取到PrintWriter对象或者通过getOutputStream()取得ServletOutputStream对象,而响应装饰器的主要做法就是重新定义这两个方法;不过在Servlet规范中,同一个请求期间,getWriter()和getOutputStream()只能择一调用,否则抛出IllegalStateException,因此在响应装饰器中,也应该遵循这个规范。
HttpServletResponseWrapper和Filter工作原理与HttpServletRequestWrapper和Filter工作原理一致