解决乱码基本上添加拦截器就可以了,get / post 提交都全部搞定。不过第二条经过我的验证,不设置视乎也可以。
第一条是在action里面对接收到的单条参数进行转换
1. String name=new String((user.getUname()).getBytes("ISO-8859-1"),"utf8");
2. 在TOMCAT 6 的 server.xml里面设置:(tomcat 7 不支持)
添加:URLEncoding="UTF-8"
<Connector port="6060" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"
useBodyEncodingForURI="true"
/>
3. 自己写Filter :必须放在web.xml的最前面。下面2个拦截器都可以用,经过测试了
<!-- struts 的中文乱码拦截器
<filter>
<filter-name>encodeFilter</filter-name>
<filter-class>com.soodeep.util.MyEncodingIntercpter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
<!-- spring的中文乱码拦截器
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
====================Struts 2 拦截器是我自定义的
=================================================
package com.soodeep.util;
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 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
public class MyEncodingIntercpter extends StrutsPrepareAndExecuteFilter
implements Filter {
private FilterConfig config = null;
private String encoding = null;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(encoding==null){
encoding = config.getInitParameter("encoding");
System.out.println("encoding = "+encoding);
}
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=" + encoding);
chain.doFilter(request, response);
}
@Override
public void destroy() {
config = null;
encoding = null;
}
}