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;
import javax.servlet.http.HttpServletResponseWrapper;
public class AllCharacterEncodeFilter implements Filter {
private FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;//为了获取配置的编码参数信息
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
//http
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
//记得配置一下
//获取配置的encoding参数信息,init中配置参数信息,
String encoding = filterConfig.getInitParameter("encoding");
if(encoding==null){
encoding="UTF-8";
}
//解决post请求方式问题
request.setCharacterEncoding(encoding);
//解决输出流的字符字节编码问题。
response.setCharacterEncoding(encoding);
response.setContentType("text/html;charset"+encoding);
//解决get方式中的编码配置问题,在放行前对request中的getparamter()的方法进行改造
MyRequest myRequest=new MyRequest(request);
//放行
chain.doFilter(myRequest, response);
}
@Override
public void destroy() {
}
}
class MyRequest extends HttpServletRequestWrapper{
public MyRequest(HttpServletRequest request) {
super(request);//???????
}
//改写此方法。
@Override
public String getParameter(String name) {
String value=super.getParameter(name);
if(value==null)
return null;
//获取请求方式
String method = super.getMethod();
if(method.equalsIgnoreCase("get")){
try {
value = new String(value.getBytes("ISO-8859-1"),super.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return super.getParameter(name);
}
}
最后不要忘记配置了!
解决全站乱码--练习代码
最新推荐文章于 2023-09-19 22:09:42 发布