`
岳乡成
  • 浏览: 120574 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

在URL中传中文参数出现乱码解决方案

阅读更多
       在B/S开发中经常会用到url传参数,而且还会有很多传中文参数的,传中文参数经常会出现乱码的问题。
        一下提供我遇到乱码问题的一个解决方案(仅供参考):
        (1)在所有的jsp页面做一下设置:
        <%@ page language="java" pageEncoding="UTF-8"%>
       <%@ page contentType="text/html;charset=UTF-8"%>
           <html>
               <head>
                   <title>中文问题</title>
                   <meta http-equiv="Content-Type"  content="text/html; charset=UTF-8">
               </head>
           </html>      
        (2)在web.xml中加如下过滤器:  org.springframework.web.filter.CharacterEncodingFilter过滤器.

        <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>


<filter>
<filter-name>encodingFilter</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>
          (3)server.xml中不要使用
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
         (4) server.xml文件加上useBodyEncodingForURI="true"
         这样应该可以搞定大多数前台的中文问题.
         <Connector port="8080"
         maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
         enableLookups="false" redirectPort="8443" acceptCount="100"
         debug="0" connectionTimeout="20000"  useBodyEncodingForURI="true"
        disableUploadTimeout="true" />
        (5)如果URL中包含中文参数要提交后台,可以用encodeURIComponent()函数进行编码。
window.location = "<%=request.getContextPath()%>/deal/toSystemDealList.action?ddlType=" + document.getElementById("ddlType").value + "&txtSelect=" +  encodeURIComponent(document.getElementById("txtSelect").value) + "&proClassId=" + document.getElementById("proClassId").value;

document.getElementById("txtSelect").value得到的是以下输入项的值(这个值可能是中文字符)
<input name="txtSelect" id="txtSelect" type="text" />
        (6)解决乱码问题还应该注意数据库的配置,下面以mysql为例进行说明:
          A.mysql配置文件:修改mysql在windows\my.ini里default-character-set=utf-8
        B.mysql里数据库和表也都设为utf8_unicode_ci
        C.数据库连结:jdbc:mysql://localhost/mydb?useUnicode=true&characterEncoding=utf-8
        注意,关键就在于此:此句中间是'&'不是'&amp;'这是因为数据库连结时,在.jsp和.java文件中应该用&号,而XML文件中需要用&amp



       
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics