通过Filter进行统一编码的实现

package com.struts3;

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;

public class setCharEncodingFilter implements Filter {

 protected FilterConfig filterConfig;

 public void init(FilterConfig filterConfig) throws ServletException {
  this.filterConfig = filterConfig;
 }

 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  if (this.filterConfig.getInitParameter("enable").equals("true")) {
   request.setCharacterEncoding(this.filterConfig.getInitParameter("encoding"));
   response.setCharacterEncoding(this.filterConfig.getInitParameter("encoding"));
  }
  chain.doFilter(request, response);
  System.out.println("do Filter!");
 }

 public void destroy() {
 }
}
web.xml配置:


    setCharEncoding
    com.struts3.setCharEncodingFilter
   
      encoding
      utf-8
   

   
      enable
      true
   

 

 
    setCharEncoding
    /*
 

 

可以通过web.xml进行Filter的encoding编码选择,以及是否使用该filter。

另外要注意jsp文件的pageEncoding如果和web.xml中的参数不一致会导致编码错误,所以建议jsp不指定pageEncoding。

你可能感兴趣的:(通过Filter进行统一编码的实现)