过滤器Filter
Posted Observer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了过滤器Filter相关的知识,希望对你有一定的参考价值。
Filter就像一个一个哨卡,用户的请求需要经过Filter,
并且可以有多个过滤器
利用过滤器我们可以实现例如自动登录、解决中文乱码问题等。
1.编写Filter:实现Filter接口,重写方法
public class MyFilter implements Filter { public void destroy() { System.out.println("过滤器销毁"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hrequest = (HttpServletRequest)request; HttpServletResponse hresponse = (HttpServletResponse)response; hrequest.setCharacterEncoding("utf-8"); hresponse.setContentType("text/html;charset=utf-8"); System.out.println("过滤器执行"); //放行 chain.doFilter(request, response); //filter执行按照配置顺序来进行 } public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
这里要注意chain.doFilter,执行后即意味着当前过滤器放行,执行下一个过滤器
2.XML配置:
<filter> <display-name>MyFilter</display-name> <filter-name>MyFilter</filter-name> <filter-class>web.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
配置方式和Servlet类似,不同的是过滤器的执行顺序是按照配置文件的先后执行,即在配置文件上方的先被执行。
3.应用
解决中文乱码问题
/** * 装饰者: * 1.增强类与被增强类实现统一接口 * 2.增强类中传入被增强类 * 3.重写需要增强的方法 * */ class EnhancedRequest extends HttpServletRequestWrapper{ private HttpServletRequest request; public EnhancedRequest(HttpServletRequest request) { super(request); this.request = request; } //getParameter重写 @Override public String getParameter(String name) { String parameter = request.getParameter(name); try { parameter=new String(parameter.getBytes("iso8859-1"),"utf-8");//转码 } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return parameter; } } public class CNFilter implements Filter { public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse rep = (HttpServletResponse) response; //增强类对象 EnhancedRequest enhancedRequest = new EnhancedRequest(req); rep.setContentType("text/html;charset=utf-8");//设置响应编码 chain.doFilter(enhancedRequest, rep); } public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
以上是关于过滤器Filter的主要内容,如果未能解决你的问题,请参考以下文章