Những điều đề cập trong bài Tiếng Việt với JSP cũng áp dụng trong vấn đề Tiếng Việt với Servlet. Việc gọi phương thức HttpServletRequest.setCharacterEncoding là thiết yếu cho form data POST method. Phương thức này phải được gọi trước phương thức HttpServletRequest.getParameter.
Cũng như với JSP, nếu dùng GET method để gửi request data tới servlet, bạn cần set URI encoding của Tomcat's HTTP Connector thành UTF-8 để form data nằm trong URL string được decode đúng bởi servlet.
Thí dụ Servlet sau đây chạy trên Tomcat 5.5.7, gói chung với NetBeans 4.1, trên Windows XP. Nếu muốn thử nghiệm với GET, bạn đổi form method "POST" thành "GET".
The information mentioned in Vietnamese with JSP is also applicable to Vietnamese with Servlet. Calling HttpServletRequest.setCharacterEncoding method is essential for form data POST method. The method must be called prior to calling HttpServletRequest.getParameter method.
Like JSP, if you use GET method to send request data to servlet, you need to set URI encoding of Tomcat's HTTP Connector to be UTF-8 so that form data embedded in URL string can be decoded correctly by servlet.
The following Servlet example runs on Tomcat 5.5.7, bundled with NetBeans 4.1, on Windows XP. To experiment with GET, you change form method "POST" to "GET".
ParamsForm.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Front end to ReadParams servlet. --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Thâu thập Request Parameters</title> </head> <body> <h1 align="center">Thâu thập Request Parameters</h1> <form action="ReadParams" method="POST"> Parameter 1: <input type="text" name="param1"><br> Parameter 2: <input type="text" name="param2"><br><br> <input type="submit"> </form> </body> </html>ReadParams.java:
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * Simple servlet that reads Unicode string parameters from the form data. */ public class ReadParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Request Parameters"; String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"; out.println(docType + "<html>\n" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" + "<head><title>" + title + "</title></head>\n" + "<body>\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li>Parameter 1: " + request.getParameter("param1") + "\n" + " <li>Parameter 2: " + request.getParameter("param2") + "\n" + "</ul>\n" + "</body></html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
References: