Struts传值中文乱码最简解决方案
又有一个新的项目快开始了,可能还是要用到SSH框架,于是决定重新总结一下SSH的使用,其实框架的使用还是很简单的,应该把更多的精力放到框架实现原理的学习上。
Struts传递中文时出现的乱码问题个人认为最简洁的解决方案是做到以下三点:
1. 将页面的 pageEncoding 设置为GBK 或 GB18030 ;
2.在web.xml中加入过滤器;
<filter>
<filter-name>GBKEncoding</filter-name>
<filter-class>com.sshnews.filter.GBKEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GBKEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-name>GBKEncoding</filter-name>
<filter-class>com.sshnews.filter.GBKEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GBKEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.编写过滤器代码:
package com.sshnews.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class GBKEncodingFilter implements Filter {
private FilterConfig config = null;
public void init(FilterConfig arg0) throws ServletException {
this.config = arg0;
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
if (this.config == null) {
return;
}
//System.out.println("filter running");
req.setCharacterEncoding("GBK");
fc.doFilter(req, res);
}
public void destroy() {
}
}
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class GBKEncodingFilter implements Filter {
private FilterConfig config = null;
public void init(FilterConfig arg0) throws ServletException {
this.config = arg0;
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
if (this.config == null) {
return;
}
//System.out.println("filter running");
req.setCharacterEncoding("GBK");
fc.doFilter(req, res);
}
public void destroy() {
}
}
OK,这样就没问题了。个人认为这是最简洁的方法了。如果写到数据库还是乱码,请参照下面的文章
JAVA写入Mysql中文乱码解决方法