maven工程下get的URI中带中文名称乱码解决

在用maven做项目时,出现了乱码问题:

http://localhost:8086/search.html?keyword=手机

经过检查发现已经在web.xml配置request等字符编码

  <filter>
      <filter-name>characterEncodingFilter</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>
      <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
    </init-param>     
  </filter>
  <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

上面相当于:

request.setCharacterEncoding("UTF-8");    
response.setCharacterEncoding("UTF-8"); 

但乱码依旧,经过百度确认,原来是因为tomcat的默认编码是:ISO-8859-1

所以需要在server.xml中更改tomcat的编码:

 <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

所以maven工程需要增加相应插件,但这个我不懂,于是采用如下方法进行:

public String search(@RequestParam(value="keyword")String keyword, 
            @RequestParam(defaultValue="1") Integer page,Model model) throws Exception{
        //解决get请求URL传值时中文乱码问题
         keyword = new String(keyword.getBytes("ISO-8859-1"),"utf-8");
      .....

}

先把字符转化为字节流,再转为相应的字符串。

 

posted @ 2017-10-02 12:25  lamsey16  阅读(418)  评论(0编辑  收藏  举报