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.125jz.com-最权威的网页设计教程站 "); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }
运行显示:??????http://www.125jz.com-???????????
解决方法:
把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即可。
125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/5111.html