Servlet返回中文需要添加 response.setCharacterEncoding("utf-8")
今天在学习(<Java 语言程序设计 进阶篇>Y.Danielliang著 340页)的时候,Servlet返回的中文为乱码,添加response.setCharacterEncoding("utf-8")后正常.
原书代码修改:
doGet方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");//!!!!!修改的地方
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<title>当前时间 time</title>");
out.println("</head>");
out.println("<form method=\"POST\" action=\"http://localhost:8080/TomcatTest1/TimeForm\" >");
out.println("Locale<select size=\"1\" name=\"locale\">");
for(int i=0;i<allLocale.length;i++){
out.println("<option value=\"" +i+"\">"+allLocale[i].getDisplayName()+"</option>");
}
out.println("</select>");
out.println("<p>Time Zone<select size=\"1\" name=\"timezone\">");
for(int i=0;i<allTimeZone.length;i++){
out.println("<option value=\""+allTimeZone[i]+"\">"+allTimeZone[i]+"</option>");
}
out.println("</select>");
out.println("<p><input type=\"submit\" value=\"Submit\">");
out.println("<input type=\"reset\" value\"Reset\"></p>");
out.println("</form>");
out.close();
}
doPost方法:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");//!!!!!修改的地方
PrintWriter out=response.getWriter();
out.println("<html>");
int localeIndex=Integer.parseInt(request.getParameter("locale"));
String timeZoneID=request.getParameter("timezone");
out.println("<head><meta charset=\"UTF-8\"><title>当前时间 time</title></head>");
out.println("<body>");
Calendar calendar=new GregorianCalendar(allLocale[localeIndex]);
TimeZone timeZone=TimeZone.getTimeZone(timeZoneID);
DateFormat dateFormat=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,allLocale[localeIndex]);
dateFormat.setTimeZone(timeZone);
out.println("当前时间: "+dateFormat.format(calendar.getTime())+"</p>");
out.println("</body></html>");
out.close();
}