1.简介
- 过滤器能够在Servlet、JSP或HTML等web组件被调用之前检查ServletRequest对象,修改请求头和请求正文的内容或者对请求进行预处理操作
- 能够在Servlet、JSP或HTML等web组件被调用之后检查ServletReponse对象,修改响应头和响应正文。
- 利用包装类ServletRequestWrapper和ServletResponseWrapper来修改ServletRequest对象和ServletResponse对象。
2.如何创建过滤器?
必须实现javax.servlet.Filter接口。
- init(FilterConfig config):过滤器初始化方法。Web应用启动时,Servlet容器首先创建FilterConfig对象(包含过滤器配置信息),然后创建Filter对象,接着调用Filter对象的init(FilterConfig config)方法,读取web.xml中的配置参数。
-
public class LoginFilter implements Filter{ private FilterConfig config; private String username; @Override public void destroy() { this.config = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //HttpServletRequest httpRequest = (HttpServletRequest)request; HttpServletResponse httpResponse = (HttpServletResponse)response; System.out.println("登录过滤器验证"); if(StringUtils.equalsIgnoreCase(username, "flyer")){ System.out.println("验证通过"); chain.doFilter(request, response); }else { System.out.println("验证被拦截"); httpResponse.sendRedirect("login.jsp"); } } @Override public void init(FilterConfig config) throws ServletException { this.config = config; username = config.getInitParameter("username"); } }
??web.xml中添加过滤器配置?
?
- <filter>??
- ????????<filter-name>loginFilter</filter-name>??
- ????????<filter-class>com.flyer.filter.LoginFilter</filter-class>??
- ????????<init-param>??
- ????????????<param-name>username</param-name>??
- ????????????<param-value>flyer</param-value>??
- ????????</init-param>??
- ????</filter>??
- ????<filter-mapping>??
- ????????<filter-name>loginFilter</filter-name>??
- ????????<url-pattern>??
- ????????????/*??
- ????????</url-pattern>??
- ????</filter-mapping>??
?
?
- <filter>??
- ????????<filter-name>encodingFilter</filter-name>??
- ????????<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>??
- ????????<init-param>??
- ????????????<param-name>encoding</param-name>??
- ????????????<param-value>??
- ????????????????UTF-8??
- ????????????</param-value>??
- ????????</init-param>??
- ????</filter>??
- ????<!--?过滤器能为所有的url过滤?-->??
- ????<filter-mapping>??
- ????????<filter-name>encodingFilter</filter-name>??
- ????????<url-pattern>??
- ????????????/*??
- ????????</url-pattern>??
- ????</filter-mapping>??
?