全站乱码过滤器简单实现
程序员文章站
2022-04-03 08:53:52
...
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//将ServletRequest和ServletResponse强转成其子类
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//对request和response对象进行增强,其中,request对象我这里采用了装饰设计模式
response.setContentType("text/html;charset=utf-8");
MyRequest myRequest = new MyRequest(request);
filterChain.doFilter(myRequest,response);
}
@Override
public void destroy() {
}
private class MyRequest extends HttpServletRequestWrapper {
HttpServletRequest request ;
boolean flag = false;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
public Map<String, String[]> getParameterMap(){
//判断当前的请求是什么请求
String method = request.getMethod();
if ("post".equalsIgnoreCase(method)){
//如果是post请求,直接设置
try {
this.request.setCharacterEncoding("utf-8");
return this.request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return super.getParameterMap();
}
}else if ("get".equalsIgnoreCase(method)){
//是get请求
Map<String, String[]> map = this.request.getParameterMap();
if (map == null){
return super.getParameterMap();
}
if (flag){
return map;
}
Set<String> keys = map.keySet();
for (String key :
keys) {
String[] values = map.get(key);
for (String value :
values) {
try {
value = new String(value.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
flag = true;
return map;
}else{
return super.getParameterMap();
}
}
public String[] getParameterValues(String name){
Map<String, String[]> map = this.getParameterMap();
if(map == null){
return super.getParameterValues(name);
}
String[] strings = map.get(name);
return strings;
}
public String getParameter(String name){
String[] parameterValues = this.getParameterValues(name);
if (parameterValues == null){
return super.getParameter(name);
}
return parameterValues[0];
}
}
}