今天研究别人的代码的时候突然发现spring的org.springframework.web.filter包下居然有个CharacterEncodingFilter.java,汗.....以前都没注意呢!不过那个看起来有点麻烦,所以下面的这个过滤器比较简单实用
java 代码
- public class CharacterEncodingFilter implements Filter {
- private String edcoding=null;
- private FilterConfig filterConfig=null;
- private boolean ignore=true;
-
- public void destroy() {
- edcoding=null;
- filterConfig=null;
- }
-
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain filterChain) throws IOException, ServletException {
- if(ignore==true||request.getCharacterEncoding()==null){
- String encoding=setCharacterEncoding(request);
- if(encoding!=null){
- request.setCharacterEncoding(encoding);
-
- }
- }
- filterChain.doFilter(request, response);
- }
-
- public void init(FilterConfig filterConfig) throws ServletException {
- this.filterConfig=filterConfig;
- this.edcoding=filterConfig.getInitParameter("encoding");
- String value=filterConfig.getInitParameter("ignore");
- if(value==null){
- this.ignore=true;
- }else if(value.equalsIgnoreCase("true")){
- this.ignore=true;
-
- }else{
- this.ignore=false;
- }
-
-
- }
- public String setCharacterEncoding(ServletRequest request){
- return this.edcoding;
- }
- }
web.xml中加以下代码
xml 代码
- <filter>
- <filter-name>CharacterEncodingFilter</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>
- <filter-mapping>
- <filter-name>CharacterEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>