《研磨struts2》 第二章 Struts2的HelloWorld 之从Servlet+JSP+JavaBean实现MVC开始 (三)

2014-11-24 08:17:05 · 作者: · 浏览: 2
cat的包中就有一个写好的处理字符集的filter,位置在下载的Tomcatd的zip包下\webapps\examples\WEB-INF\classes\filters文件夹下面,名称是SetCharacterEncodingFilter.java。

为了示例简单,去掉了所有的注释,
代码如下:

java代码:
查看复制到剪贴板打印
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;

public void destroy() {
this.encoding = null;
this.filterConfig = null;
}

public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}

public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");

java代码:
查看复制到剪贴板打印
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}

然后在web.xml中进行配置,示例如下:

java代码:
查看复制到剪贴板打印

encoding
filters.SetCharacterEncodingFilter

encoding
gb2312




encoding
/*

再次运行示例,会发现已经可以正常使用中文了。

私塾在线网站