程序代码:
package util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.HttpServletRequestWrapper;
public class EncodingFilter implements Filter{
String encoding;
public void destroy() {
}
//初始化
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("encoding");
System.out.println(encoding);
}
public void doFilter(ServletRequest sReq, ServletResponse sRes,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)sReq;
String m = request.getMethod();
if("post".equalsIgnoreCase(m)){//如果是post 提交
System.out.println("post提交");
request.setCharacterEncoding(encoding);//("utf-8")
}else if("get".equalsIgnoreCase(m)){//get 提交
//System.out.println("get提交");
request = new MyRequest(request);
}
chain.doFilter(request, sRes);
}
public class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest myReq;
public MyRequest(HttpServletRequest request) {
super(request);
myReq = request;
}
public String getParameter(String name){
String s = myReq.getParameter(name);
//System.out.println("编码转换前:"+s);
try {
if(s!=null){
s = new String(s.getBytes("ISO-8859-1"),"UTF-8");
}
//System.out.println("编码转换后: "+s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
}
}
------------------------------------
另外还要在web.xml 中配置:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>jenwin.filters.EncodingFilter</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>