步驟一:編輯Tomcat的配置文件conf/server.xml在用於接受客戶端語法的Connector<connector></connector>標籤中添加URIEncoding="UTF-8"屬性,該屬性用來解決GET中的編碼問題。
- <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
步驟二:在每個需要提交表單參數的JSP/Servlet之前加入下列代碼來設置字符集,用於搞定POST請求:
- request.setCharacterEncoding("UTF-8");
這樣基本就搞定了字符亂碼問題了,實現上述問題的要求是所有的網頁編碼必須是UTF-8編碼既。
在JSP中:
- <%@page contentType="text/html" pageEncoding="UTF-8"%>
在Servlet中:
- response.setContentType("text/html;charset=UTF-8");
在所有的網頁中:
- <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
附測試代碼:
- Document : zc
- Created on : 2007-12-22, 17:20:24
- Author : 啊春
- -->
- >
- <html>
- <head>
- <title>title>
- <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
- head>
- <body>
- <form action="/wat1/t1" method="GET">
- 姓名:<input type="text" name="name" value="" size="20" />
- 密碼:<input type="password" name="passwd" value="" size="20" />
- <input type="submit" value="註冊" />
- form>
- <br />
- <form action="/wat1/t1" method="POST">
- 姓名:<input type="text" name="name" value="" size="20" />
- 密碼:<input type="password" name="passwd" value="" size="20" />
- <input type="submit" value="註冊" />
- form>
- body>
- html>
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- try {
- /* TODO output your page here
- out.println("");
- out.println("");
- out.println("");
- out.println("");
- out.println("");
- out.println("
Servlet t1 at " + request.getContextPath () + "
"); - out.println("");
- out.println("");
- */
- out.println("Hello 歡迎你的註冊");
- request.setCharacterEncoding("UTF-8");
- String str = request.getParameter("name");
- out.println(str);
- out.println(request.getParameter("passwd"));
- } finally {
- out.close();
- }
- }