java web中如何通过filter 设置全局编码

在这两个包装类基础上,继承HttpServletRequestWrapper ,覆盖需要增强的方法即可。

Filter中,对request对象进行包装,增强获得参数的方法:

getParameter

getParameterValues

getParameterMap

ServletResponseWrapper HttpServletResponseWrapper 提供了对response 对象包装,继承 HttpServletResponseWrapper ,覆盖需要增强response的方法。


public class EncodingFilter implements Filter {


public void destroy() {


}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;

// 2.操作
HttpServletRequest myrequest = new MyRequest(request); // 增强后的request,解决了编码问题
response.setContentType("text/html;charset=utf-8");

// 3.放行
chain.doFilter(myrequest, response);
}


public void init(FilterConfig filterConfig) throws ServletException {


}
}

// 装饰类
class MyRequest extends HttpServletRequestWrapper {

private HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
// 重写关于获取请求参数的方法.
@Override
public String getParameter(String name) {
Map<String, String[]> map = getParameterMap();
if (name == null) {
return null;
}
String[] st = map.get(name);
if (st == null || st.length == 0) {
return null;
}
return st[0];
}
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> map = getParameterMap();
if (name == null) {
return null;
}
String[] st = map.get(name);
return st;
}

private boolean flag = true;
@Override
public Map getParameterMap() {
// 1.得到所有请求参数的Map集合
Map<String, String[]> map = request.getParameterMap(); // 有编码问题.
// 2.解决编码问题.
if (flag) {
for (String key : map.keySet()) {
String[] values = map.get(key);
for (int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("iso8859-1"),
"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
flag = false;
}
return map;
}
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页