例jsp中传入的参数名字:shortname
情况(1):和方法2针对的情况一样 如果是第3种情况的话就不适用了
java后台代码这样处理 String str = new String(shortname.getBytes("iso-8859-1"),"UTF-8") ; 不需要对jsp页面的参数编码
情况(2)针对使用Ajax get请求时参数不附加在url后:如 $.ajax{type:get,data:shortname:shortname...... }
jsp页面参数这样处理 encodeURIComponent(shortname)
java后台代码这样处理 String str = URLDecoder.decode(shortname, "utf-8");
情况(3)get 提交针对于参数附加在url后面:如:url:/ajax/a.action?shortname=shortname
jsp页面参数这样处理 encodeURI((encodeURI(shortname))) 这样也可以encodeURI(shortname) 。。。。。
java后台代码这样处理 String str = URLDecoder.decode(shortname, "utf-8");
针对第2和第3种情况 如果前台还需要这个参数shortname 一直在前后台传来传去的话,要注意下 后台传到前台时也要对这个参数shortname进行编码:
URLEncoder.encode(URLEncoder.encode(shortname, "utf-8"), "utf-8") 还有就是情况2,3避免乱码,可以改用post请求!
不过感觉最简单的方法还是用过滤器了:过滤器类如下
package zz; 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; /** * Filter that sets the character encoding to be used in parsing the * incoming request */ public class SetCharacterEncodingFilter implements Filter { protected String encoding = null; protected FilterConfig filterConfig = null; public void destroy() {} public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); } /** * Select and set(if specified) the character encoding to be used to * interpret request parameters for this request */ public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws IOException,ServletException { request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); chain.doFilter(request,response); } }web.xml中的配置加上下面几句话就行了:
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>com.bigdata.financial.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>