以前都是用公司現成的架構開發一些項目,但最近自己利用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...哈哈