servlet中文顯示亂碼:
第一種情況:servlet中輸出中文字符,如:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" 中國網頁設計http://www.xin126.cn-最權威的網頁設計教程站 ");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
運行顯示:??????http://www.xin126.cn-???????????
解決方法:
把response.setContentType("text/html");改為response.setContentType("text/html;charset=UTF-8");
第二種情況:servlet接收表單傳值並顯示,表單字段含中文。
如:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
String name=request.getParameter("name");//接收表單傳遞的參數值,含中文。
out.println("hello "+name);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
解決方法:在servlet程序中加上以下代碼就可以了:
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
如果頁面編碼是gb2312只需將以上代碼中的UTF-8換成gb2312即可。
*