SSH傳參中文亂碼問題解決方法

   本身編寫filterhtml

public class CharsetEncodingFilter implements Filter {mysql

private String charsetEncoding = null;web

private String enable = null;spring

public void destroy() {sql

this.charsetEncoding = null;數據庫

this.enable = null;tomcat

}app


public void doFilter(ServletRequest request, ServletResponse response,this

FilterChain arg2) throws IOException, ServletException {編碼

if(this.enable.equals("true")) {

request.setCharacterEncoding(charsetEncoding);

response.setContentType("text/html;charset=" + charsetEncoding);

arg2.doFilter(request, response);

}

}


public void init(FilterConfig config) throws ServletException {

this.charsetEncoding = config.getInitParameter("CharsetEncoding");

this.enable = config.getInitParameter("enable");

}

}

說明:上面的encoding根據你用的編碼類型決定,在這裏我用utf-8

  web.xml中配置上面的filter

<filter>

        <filter-name>charFilter</filter-name>

        <filter-class>com.landtofrest.util.EncodingFilter</filter-class>

    </filter>

    <filter-mapping>

        <filter-name>charFilter</filter-name>

        <url-pattern>/*</url-pattern>

</filter-mapping>

說明:<filter-class>是上面filter類的路徑:包.類名

      <filter-name>命名隨便

      直接在web.xml配置以下:

<filter>

<filter-name>SpringCharacterEncodingFilter</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>SpringCharacterEncodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

  tomcat中配置server.xml,個人是MYEclipse自帶的。我在myEclipse裏面找不到tomcatserver.xml。而是在workspace->.metadata->.me_tcat->conf->server.xml那裏找到

修改:

 <Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" URIEncoding="UTF-8"/>

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>

 

說明:紅色部分是要添上去的

 

  應該能夠運行了!?頁面參數傳到action在控制檯輸出已經不是亂碼,但是數據庫查詢仍是查不到記錄,後面查了不少資料,才知道,mysql中編碼也是有講究的。

找到mysql安裝目錄,打開my.ini文檔,把這句default-character-set=Latin1改爲這樣子default-character-set=utf8。注意是default-character-set有兩句喲。

 

說明:若是在建表時下面的第⑤步已經作了的話,第④步是沒有必要滴。

若是已經作了第④步,第⑤步中建表時有沒有必要在指定引擎後再添加DEFAULT CHARSET =utf8,這個我尚未試驗

 

  應該能夠運行了!?仍是不行。

由於我在mysql用命令【show create table 表名;】查看本身在建表的時候默認的是Latin1,因此得改過來,建表時應該【create 表名()ENGINE=引擎 DEFAULT CHARSET =utf8;】。

或者這樣比較麻煩,能夠有另外一種辦法就是在建表以前用【set names utf8;】命令,這樣在關閉mysql以前都用utf8而不用再在建每一個表都是這樣。

   你會發現若是用【set names utf8;】而沒改的話,用insert插入數據時就出現data too long的錯誤,因此,用想要插入得用【set names gb2312或者gbk;】,習慣用gbk,這樣就能夠插入數據了。

相關文章
相關標籤/搜索