package servlet;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
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 EncodeFilter implements Filter{
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req=(HttpServletRequest)arg0;
//得到页面提交的方式
String method=req.getMethod();
//请求编码转换
if(method.equalsIgnoreCase("post")){
req.setCharacterEncoding(this.newEncode);
}else{
//得到一个map集合
Map map=req.getParameterMap();
Collection vs=map.values();
Iterator it=vs.iterator();
while(it.hasNext()){
Object obj=it.next();
String[] ss=(String[])obj;
for (int i = 0; i < ss.length; i++) {
ss[i]=new String(ss[i].getBytes(this.oldEncode),this.newEncode);
}
}
}
// 更改响应编码格式
arg1.setContentType(this.respEncode);
//打开过滤器
arg2.doFilter(arg0, arg1);
}
//原来的编码格式
String oldEncode;
//更改后请求的编码格式
String newEncode;
//响应的编码格式
String respEncode;
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
//从配置文件拿到设置的编码格式
this.oldEncode=arg0.getInitParameter("oldEncode");
this.newEncode=arg0.getInitParameter("newEncode");
this.respEncode=arg0.getInitParameter("respEncode");
}
}
配置文件:
<!-- 编码格式的配置文件 -->
<filter>
<filter-name>Encode</filter-name>
<filter-class>servlet.EncodeFilter</filter-class>
<!-- 原来的编码格式设置 -->
<init-param>
<param-name>oldEncode</param-name>
<param-value>iso8859-1</param-value>
</init-param>
<!-- 更改后请求的编码格式设置 -->
<init-param>
<param-name>newEncode</param-name>
<param-value>GBK</param-value>
</init-param>
<!-- 响应的编码格式设置 -->
<init-param>
<param-name>respEncode</param-name>
<param-value>text/html;charset=GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>