package com.hongyou.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;
public class HyCharEncodingFilter implements Filter
{
private String charSet;
public void init(FilterConfig filterConfig) throws ServletException {
charSet = filterConfig.getInitParameter("charSet");
if(charSet == null || charSet.length() < 1){
charSet = "UTF-8";
}
System.out.println("CharEncodingFilter--字符集: " + this.getCharSet());
}
public void destroy() {
this.setCharSet(null);
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding(this.getCharSet());
chain.doFilter(req, res);
}
public String getCharSet() {
return charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
}
web.xml
<filter>
<filter-name>CharEncodingFilter</filter-name>
<filter-class>com.hongyou.filter.HyCharEncodingFilter</filter-class>
<init-param>
<param-name>charSet</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>