分析解決JSP頁面顯示中文亂碼的問題

儘量用post提交,不要用問號拼接參數的方式,就不會亂碼了

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%  request.seCharacterEncoding("UTF-8");  %>   
<html>   
    <head>   
   		 <title>JSP的中文處理</title>   
  		 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">   
    </head>   
     
    <body>   
    <%=request.getParameter("name")%> 
   <!-- 實在不行,還可以強制轉 -->
	var str = <%= new String(request.getParameter("參數名").getBytes("iso-8859-1"), "utf-8"); %>
    </body>   
</html>

◆charset=UTF-8的作用是指定JSP向客戶端輸出的編碼方式爲“UTF-8”;
◆pageEncoding=“UTF-8”,爲了讓JSP引擎能正確地解碼含有中文字符的JSP頁面,這在LINUX中很有效;
◆request.setCharacterEncoding(“UTF-8”);是對請求進行了中文編碼。

----------------------------------- 沒有感情的分割線 ----------------------------------------
解決問題,先要研究問題,URL傳中文參數爲什麼會出現亂碼?

原因:Http請求傳輸時將url以ISO-8859-1編碼,服務器收到字節流後默認會以ISO-8859-1編碼來解碼成字符流(造成中文亂碼)

解決辦法:我們需要把request.getParameter(“參數名”)獲取到的字符串先用ISO-8859-1編碼成字節流,然後再將其用utf-8解碼成字符流

方法一、代碼:(在 .jsp 頁面寫java代碼,強制轉)

<!--.jsp 頁面寫這個java代碼。需要用 <%= %> 括起來 -->
var str = <%= new String(request.getParameter("參數名").getBytes("iso-8859-1"), "utf-8"); %>

ISO-8859-1編碼是單字節編碼,向下兼容ASCII.
這是通過轉碼的方式處理亂碼問題,我們也可以通過Tomcat配置文件,設置URL編碼集(URIEncoding)設置編碼,這種方法也是一勞永逸的,

方法二、修改Tomcat/conf 目錄下 server.xml(這樣配置,會解決get請求中的 中文亂碼問題。)

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

加這個:URIEncoding=“UTF-8”
重啓Tomcat

方法三、在配置文件中添加配置,在web.xml中添加一段代碼(這樣配置,會解決post請求中的 中文亂碼問題。)

<!-- 配置中文亂碼的問題 -->
<filter>
       <filter-name>encodingFilter</filter-name>
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <async-supported>true</async-supported>
           <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
           </init-param>
</filter>
<filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章