Servlet返回中文

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();
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值