以前都是用公司现成的架构开发一些项目,但最近自己利用Struts+Spring+hibernate开发项目的时候才发现自己会的技术太少了,真是问题多多啊,革命尚未成功,同志还需努力。。。。
刚开始的时候,将JSP页面利用<%@page contentType="text/html; charset=GBK"%>转换页面上汉字的编码方式,页面上的汉字可以正常显示了,但JSP页面上的中文数据传入BEAN的时候还是出现乱码问题,从action里面get出来的汉字都是乱码,在网上查找了一些资料,发现可以在formBean里面添加toGBK方法:
- private String toGBK(String str)throws java.io.UnsupportedEncodingException
- {
- return new String(str.getBytes("ISO-8859-1"),"GBK");
- }
然后在每个set方法中将传进来的值进行转换,如:
- public void setXgrq(Date xgrq)
- {
- this.xgrq = this.toGBK(xgrq).trim;
- }
但这样虽然解决了通过form传递中文的问题,但不能解决其他方式传值问题(不通过form),如:通过location.href传值的方式,于是想到写一个filter来过滤所有的传值调用,由于以前没有写过filter,所以现在也把filter的代码帖出来,便于记忆:
- package com.wmf.struts;
- import java.io.IOException;
- import javax.servlet.*;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletResponse;
- public class servfilter extends HttpServlet implements Filter {
- protected String encoding = "GBK";
- protected FilterConfig filterConfig;
- public void destroy() {
- // TODO 自动生成方法存根
- this.encoding = null;
- this.filterConfig = null;
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain filterChain)
- throws IOException, ServletException {
- // TODO 自动生成方法存根
- request.setCharacterEncoding(this.encoding);
- response.setCharacterEncoding(this.encoding);
- ((HttpServletResponse)response).setHeader("Pragma","No-cache");
- ((HttpServletResponse)response).setHeader("Cache-Control","no-cache");
- ((HttpServletResponse)response).setHeader("Expires","0");
- filterChain.doFilter(request, response);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO 自动生成方法存根
- this.filterConfig = filterConfig;
- this.encoding = this.filterConfig.getInitParameter("encoding");
- }
- }
在web.xml中也需要增加如下配置:
- <filter>
- <filter-name>servfilter</filter-name>
- <filter-class>com.wmf.struts.servfilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>GBK</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>servfilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </filter>
结果测试了一把,单步调试的时候程序已经跳入filter了,但location.href传递的中文值乱码依旧,无奈啊。。。
实在没办法了,就上CSDN找高手求救,哈哈,下面是他们的回复:
要是tomcat,则编码问题建议统一用utf-8,我们就一直使用的很好
需要在server.xml里面的connector里面务必设置如下参数:
URIEncoding="UTF-8" useBodyEncodingForURI="true"
**************************************************************
传值出现中文乱码你使用的是tomcat的吧
是url传值中文乱码吧
先把 server.xml 中的<Connector 中加入 URIEncoding="GBK"
url传中文最好先转换下编码
URLEncoder.encode("汉字","GBK")
接受后在解码
URLDecoder.decode("汉字","GBK");
果然,在Connector中加入URIEncoding="UTF-8" useBodyEncodingForURI="true"之后,问题统统搞定了,无论是form还是location.href传的中文参数都正确了,o(∩_∩)o...哈哈