java web中配置Filter解决jsp中文乱码问题
今天在做DynaActionForm练习的时候,在表单提交时,遇到了提交中文出现乱码的问题。虽然以前解决过类似的问题,但总是没有记录相关的笔记。后来在网的找了一大堆的文章看了以后,大部都是乱说一通,感觉行得通,但太麻烦了,于是找到自己以前做过的小项目中,看了一下以前设计的Filter,让站点内所有的编码都为utf-8的形式输出!于是也在自己DynaActionForm的练习中配置了一下Filter,之后,整个Project里面的东西,都没有出现乱码的问题了。下面说一下具体的做法: 建立一个实现Filter接口的类。这个类需要三个方法,分别是:doFilter、init和destroy。doFilter方法包含主要的过滤代码,init方法建立设置操作,而destroy方法进行清除。 比如我建立的是FilterChar.java package com.gtxy.dynaActionForm.web.filter;
import java.io.IOException;
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.HttpServletResponse;
/**
- 以 UTF-8 输入输出
- @author ZhongHuiQiang
*/ public class FilterChar implements Filter {
private String config;
public void destroy() { this.config = null; }
/** * name="FilterChar" * init-param name="config" value="utf-8" * mapping url-pattern="/*" */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req; req = (HttpServletRequest) request;
HttpServletResponse res;
res = (HttpServletResponse) response;
req.setCharacterEncoding(config);
res.setCharacterEncoding(config);
chain.doFilter(req, res);
}
/** * 获得web.xml中初始化的参数 */ public void init(FilterConfig config) throws ServletException { this.config = config.getInitParameter("chars"); }
}
OK,FilterChar类写完后,就要配置web.xml了! 在web.xml里面,最主要是下面这段代码 FilterChar com.gtxy.dynaActionForm.web.filter.FilterChar chars utf-8 FilterChar /*
转自:http://webview.blog.51cto.com/969902/245781