在Tomcat6.0中關於JSP/Servlet表單亂碼的一個解決方法

步驟一:編輯Tomcat的配置文件conf/server.xml在用於接受客戶端語法的Connector<connector></connector>標籤中添加URIEncoding="UTF-8"屬性,該屬性用來解決GET中的編碼問題。

xml 代碼
  1. <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />



步驟二:在每個需要提交表單參數的JSP/Servlet之前加入下列代碼來設置字符集,用於搞定POST請求:

java 代碼
  1. request.setCharacterEncoding("UTF-8");



這樣基本就搞定了字符亂碼問題了,實現上述問題的要求是所有的網頁編碼必須是UTF-8編碼既。
在JSP中:

jsp 代碼
  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>

在Servlet中:

java 代碼
  1. response.setContentType("text/html;charset=UTF-8");

在所有的網頁中:

html代碼
  1. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">



以上測試在Tomcat 6.0.14、IE6.0、FireFox2.0.13及Opera9.25中測試通過,開發環境使用netBeans 6.0

附測試代碼:

html代碼
  1. Document : zc
  2. Created on : 2007-12-22, 17:20:24
  3. Author : 啊春
  4. -->
  5. >
  6. <html>
  7. <head>
  8. <title>title>
  9. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  10. head>
  11. <body>
  12. <form action="/wat1/t1" method="GET">
  13. 姓名:<input type="text" name="name" value="" size="20" />
  14. 密碼:<input type="password" name="passwd" value="" size="20" />
  15. <input type="submit" value="註冊" />
  16. form>
  17. <br />
  18. <form action="/wat1/t1" method="POST">
  19. 姓名:<input type="text" name="name" value="" size="20" />
  20. 密碼:<input type="password" name="passwd" value="" size="20" />
  21. <input type="submit" value="註冊" />
  22. form>
  23. body>
  24. html>

 

java 代碼
  1. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  2. throws ServletException, IOException {
  3. response.setContentType("text/html;charset=UTF-8");
  4. PrintWriter out = response.getWriter();
  5. try {
  6. /* TODO output your page here
  7. out.println("");
  8. out.println("");
  9. out.println("");
  10. out.println("");
  11. out.println("");
  12. out.println("

    Servlet t1 at " + request.getContextPath () + "

    ");
  13. out.println("");
  14. out.println("");
  15. */
  16. out.println("Hello 歡迎你的註冊");
  17. request.setCharacterEncoding("UTF-8");
  18. String str = request.getParameter("name");
  19. out.println(str);
  20. out.println(request.getParameter("passwd"));
  21. } finally {
  22. out.close();
  23. }
  24. }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章