标签:extend throw utf-8 over logs 实现 exception getc encoding
过滤器
生命周期:初始化 -----过滤-------销毁
作用:过滤url ,特定字符
创建方式:实现一个接口继承Filter
package com.baidu.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class Demo01 implements Filter { public void destroy() { System.out.println("过滤销毁"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("请求过滤"); MyHttpServletRequest msr=new MyHttpServletRequest((HttpServletRequest)request); chain.doFilter(msr, response); System.out.println("响应过滤"); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { System.out.println("过滤器初始化"); } }
配置过滤器(web.xml)
和配置servlet相似。
<filter> <filter-name>Demo01</filter-name> <filter-class>com.baidu.filter.Demo01</filter-class> </filter> <filter-mapping> <filter-name>Demo01</filter-name> <url-pattern>/*</url-pattern>//可以设置经过过滤器的url /*表示项目下的所有路径都得经过过滤器 </filter-mapping>
过滤器在web中的位置
浏览器 < ------------ > 过滤器 < ------------ > 服务器
注意事项
1.配置文件中会配置Filter过滤器的位置只要符合其位置就会经过过滤器
2.请求完成以后响应动作也会经过过滤器
使用过滤器来修改编码格式,这样就不需要用每个servlet中去修改编码格式了
package com.baidu.filter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class MyHttpServletRequest extends HttpServletRequestWrapper { private HttpServletRequest request; public MyHttpServletRequest(HttpServletRequest request) { super(request); this.request=request; } @Override public String getParameter(String name) { //判断提交方式(get/post) String method = request.getMethod(); if ("Get".equalsIgnoreCase(method)) { String value = super.getParameter(name); try { value = new String(value.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return value; } if ("post".equalsIgnoreCase(method)) { try { System.out.println(request.getCharacterEncoding()); request.setCharacterEncoding("UTF-8"); //value = super.getParameter(name); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return super.getParameter(name); } }
标签:extend throw utf-8 over logs 实现 exception getc encoding
原文地址:http://www.cnblogs.com/fjkgrbk/p/Filter.html