package cn.itcast.filters;
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;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {
}
public void doFilter(ServletRequest requ, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) requ;
HttpServletResponse response = (HttpServletResponse) resp;
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
MyWraaper mw=new MyWraaper(request);
chain.doFilter(mw, response);
}
class MyWraaper extends HttpServletRequestWrapper {
private HttpServletRequest request;
public MyWraaper(HttpServletRequest request) {
super(request);
this.request=request;
}
public String getParameter(String name) {
String method = request.getMethod();
String value=request.getParameter(name);
if ("GET".equals(method)) {
try {
if(value!=null&&!"".equals(value)){
value = new String(value.getBytes("iso-8859-1"), "utf-8");
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return value;
}
}
public void destroy() {
}
}