JSP頁面亂碼問題

來源:互聯網
上載者:User

標籤:div   gb2312   head   發送   except   orm   統一   code   request   

1、表單提交中文時出現亂碼

下面是一個提交頁面(submit.jsp),代碼如下:

<html>   

<head>   

<title>JSP的中文處理</title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">   

</head>

<body>

<form name="form1" method="post" action="process.jsp">   

<div align="center">   

<input type="text" name="name">   

<input type="submit" name="Submit" value="Submit">   

</div>

</form>

</body>

</html>

下面是處理頁面(process.jsp)代碼:

<%@ page contentType="text/html; charset=gb2312"%>   

<html>

<head>

<title>JSP的中文處理</title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">   

</head>

<body>

<%=request.getParameter("name")%>   

</body>

</html>

如果submit.jsp提交英文字元能正確顯示,如果提交中文時就會出現亂碼。原因:瀏覽器預設使用UTF-8編碼方式來發送請求,而UTF-8和GB2312編碼方式表示字元時不一樣,這樣就出現了不能識別字元。解決辦法:通過request.seCharacterEncoding("gb2312")對請求進行統一編碼,就實現了中文的正常顯示。修改後的process.jsp代碼如下:

<%@ page contentType="text/html; charset=gb2312"%>   

<%   

request.seCharacterEncoding("gb2312");   

%>   

<html>

<head>

<title>JSP的中文處理</title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">   

</head>

<body>

<%=request.getParameter("name")%>   

</body>

</html>

2、資料庫連接出現亂碼

只要涉及中文的地方全部是亂碼,解決辦法:在資料庫的資料庫URL中加上useUnicode=true&characterEncoding=GBK就OK了。

3、資料庫的顯示亂碼

在mysql4.1.0中,varchar類型,text類型就會出現中文亂碼,對於varchar類型把它設為binary屬性就可以解決中文問題,對於text類型就要用一個編碼轉換類來處理,實現如下:

public String iso2gb(String qs)   

{   

try{   

if (qs == null) return "NULL";   

else   

{   

return new String(qs.getBytes("iso-8859-1"),"gb2312");   

}   

}   

catch(Exception e){   

System.err.println("iso2gb error:"+e.getMessage());   

}   

return "NULL";   

}   

public String gb2iso(String qs)   

{   

try   

{   

if (qs == null) return "NULL";   

else {   

return new String(qs.getBytes("gb2312"),"iso-8859-1"); }   

}   

catch(Exception e){ System.err.println("gb2iso error:"+e.getMessage());}   

return "NULL";   

此文僅供參考。

JSP頁面亂碼問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.