使用过滤器统一全站编码

在web开发中,过滤器是一项非常激动人心的技术,它可以对所有的访问进行控制,通过这些特性,我们可以用来实现很多的需求。常见的有记住用户名密码、统一全站编码等等。本文就利用过滤器+装饰器实现统一全站编码做简单的介绍。

首先需要对jsp和servlet中的编码有一定的了解,具体可以看这篇文章:JSP编码以及乱码解决总结
实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class EncodingFilter implements Filter{
// filter初始化参数
private FilterConfig config ;
private static Log log = LogFactory.getLog(EncodingFilter.class);

public void destroy() {
// do nothing
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{

// 获取自定义编码
String encode = config.getInitParameter("encode");
if (encode == null){
encode = "utf-8";
}
HttpServletRequest req =(HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 使用装饰器
MyReq myReq = new MyReq(req);
chain.doFilter(myReq, resp);
}

public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
}

/**
* 装饰器模式
* @author: xlli
* @CreateDate: 2016-3-27 上午12:22:01
* @version: 1.0
*/

class MyReq extends HttpServletRequestWrapper{
private HttpServletRequest req;

public MyReq(HttpServletRequest request) {
super(request);
this.req = request;
}

@Override
public String getParameter(String name) {
// post请求
if (req.getMethod().equalsIgnoreCase("post")){
return req.getParameter(name);
}
// get请求
String value = req.getParameter(name);
if (value == null){
return null;
}
try {
value = new String(req.getParameter(name).getBytes("iso8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
log.error(new Date().getTime() + "EncodingFilter编码转化失败",e);
};
return value;
}
}

}