分两种情况:
1. GET方式
这种方法目前我只找到一种方案解决,就是利用
1 value =new String(value.getBytes("ISO8859-1"),"UTF-8");
因为JSP在传参数值时是用ISO8859-1,没办法,只能这样做。
可以选择在页面上写,也可以选择在JAVA文件处理参数值时做转换。
2. POST方式
自己写一个Filter,来设置编码。参考http://heisetoufa.iteye.com/blog/227365
1 package edu.whu.ress.CustomFilter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 13 public class EncodingFilter implements Filter { 14 protected FilterConfig filterconfig; 15 private String targetEncoding = "UTF-8"; 16 17 public void init(FilterConfig config) throws ServletException { 18 this.filterconfig = config; 19 this.targetEncoding = config.getInitParameter("encoding"); 20 } 21 22 public void doFilter(ServletRequest srequest, ServletResponse sresponse, 23 FilterChain chain) throws IOException, ServletException { 24 HttpServletRequest request = (HttpServletRequest)srequest; 25 26 request.setCharacterEncoding(targetEncoding); 27 chain.doFilter(srequest,sresponse); 28 sresponse.setCharacterEncoding(targetEncoding); 29 30 31 } 32 33 public void setFilterConfig(final FilterConfig filterConfig){ 34 this.filterconfig=filterConfig; 35 } 36 37 public void destroy() { 38 this.filterconfig = null; 39 40 } 41 }
在web.xml中增加filter与filtermapping,注意,用于编码的Filter要放在Struct的FilterDispatcher前面
1 <filter> 2 <filter-name>characterEncoding</filter-name> 3 <filter-class>CustomFilter.EncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>UTF-8</param-value> 7 </init-param> 8 <init-param> 9 <param-name>forceEncoding</param-name> 10 <param-value>true</param-value> 11 </init-param> 12 </filter> 13 14 <filter-mapping> 15 <filter-name>characterEncoding</filter-name> 16 <url-pattern>/*</url-pattern> 17 </filter-mapping>
这样基本就可以解决post方式中文乱码的问题。