java 代码
public class SetCharacterEncodingFilter implements Filter {
protected String encoding=null;
protected FilterConfig filterConfig=null;
protected boolean ignore=true;
//destroy方法
public void destroy() {
this.encoding=null;
this.filterConfig=null;
}
/* 选择设置使用的字符编码
* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//选择使用的字符编码
if(ignore||(request.getCharacterEncoding()==null)){
String encoding=selectEncoding(request);
if(encoding!=null){
request.setCharacterEncoding(encoding);
}
}
//将控制权交给下一个Filter
chain.doFilter(request, response);
}
/* 将这个filter放置在服务中
* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig=filterConfig;
this.encoding=filterConfig.getInitParameter("encoding");
String value=filterConfig.getInitParameter("ignore");
if(value==null){
this.ignore=true;
}else if(value.equalsIgnoreCase("true")){
this.ignore=true;
}else if(value.equalsIgnoreCase("yes")){
this.ignore=true;
}else {
this.ignore=false;
}
}
protected String selectEncoding(ServletRequest request){
return this.encoding;
}
web
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>com.*.*.*.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gbk</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>