注:该过滤器只对post提交方式有效。


java代码:

package 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 CharacterEncodingFilter implements Filter{
	  private String charEncoding;
	 
	public void init(FilterConfig filterConfig) throws ServletException {
		charEncoding = filterConfig.getInitParameter("encoding");
		if(charEncoding==null||charEncoding.isEmpty())
		{
			 charEncoding = "UTF-8";
		}
		System.out.println("字符编码过滤器初始化完毕  Encoding=" +charEncoding);
	}
	 
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		
		System.out.println("有请求到来,开始执行字符编码过滤器....");
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		httpRequest.setCharacterEncoding(charEncoding);
		filterChain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

web.xml文件配置:

  <filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


您的十分满意是我追求的宗旨。

您的一点建议是我后续的动力。








本文转载:CSDN博客