Servlet:
package cn.hbsi.web.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;
import javax.servlet.http.HttpServletResponse;
public class CharSetEncodingFilter implements Filter {
private FilterConfig filterConfig;
public void destroy() {
// TODO Auto-generated method stub
}
private String defaultCharset="utf-8";
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//解决乱码
//恢复子类的原有属性
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse rep=(HttpServletResponse)response;
//初始化参数
String charset=filterConfig.getInitParameter("encode");
if(charset==null){
charset=defaultCharset;
}
request.setCharacterEncoding(charset);
rep.setCharacterEncoding(charset);
rep.setContentType("text/html;charset="+charset);
chain.doFilter(req, rep);
}
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig=filterConfig;
}
}
描述文件:
<filter>
<filter-name>CharSetEncodingFilter</filter-name>
<filter-class>cn.hbsi.web.filter.CharSetEncodingFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharSetEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>