/**
* Tomcat
GET方式表单提交乱码解决。
* @author BeanSoft
*
*/
public class
TomcatFormFilter implements Filter {
public void destroy() {
//
TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain) throws IOException, ServletException {
//
1. ServletRequest 转成 HttpServletRequest
HttpServletRequest req =
(HttpServletRequest)request;
// 2.
如果是GET,就生成一个Wrapper对象,覆盖获取参数的方法进行转码
if("GET".equalsIgnoreCase(req.getMethod()))
{
req = new MyRequest(req);
}
// 3.
如果是POST,request.setCharacterEncoding("UTF-8")
else
if("POST".equalsIgnoreCase(req.getMethod())) {
req.setCharacterEncoding("UTF-8");
}
//
4.调用chain.doFilter继续向后执行
chain.doFilter(req, response);
}
public void init(FilterConfig arg0) throws ServletException {
//
TODO Auto-generated method stub
}
}
/**
* 包装器,覆盖 getParameter()和 getParameterValues() 这两个方法来进行转码。
*
@author BeanSoft
*
*/
class MyRequest extends
HttpServletRequestWrapper {
public MyRequest(HttpServletRequest request) {
super(request);
//
TODO Auto-generated constructor stub
}
/**
* 字符串转码。
* @param input 输入字符串
* @param srcEncoding 源字符串的编码
* @param
targetEncoding 目标编码
* @return 转换过的内容
*/
public String
changeEncoding(String input, String srcEncoding, String targetEncoding) {
try
{
// 1. 获取源编码的bytes[]
byte[] data =
input.getBytes(srcEncoding);
// 2. 将bytes[]按照制定编码转换为String
return
new String(data, targetEncoding);
} catch
(UnsupportedEncodingException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
return input;
}
@Override
public String getParameter(String name) {
String
value = super.getParameter(name);
if(value != null) {
value
= changeEncoding(value, "ISO8859-1", "UTF-8");
}
return
value;
}
@Override
public String[] getParameterValues(String name) {
String[]
values = super.getParameterValues(name);
if(values != null
&& values.length > 0) {
for (int i = 0; i <
values.length; i++) {
String value = values[i];
values[i]
= changeEncoding(value, "ISO8859-1", "UTF-8");
}
}
return
values;
}
}