令人恼火的UTF-8中文问题
我实在是气不过了,再在这里问一下:
在Tomcat 5.5中,我写了个Servlet,希望能读取在URL中的中文数据,如:http://localhost:8080/csj/ch04/testServlet?name=牛人,结果竟得到的是一堆乱码,于是查完所有google,baidu,找到一些网上的解决方法,结果还是不行,大家教教我该怎么做?
我的做法是这样的:
在tomcat中,修改:conf/server.xml,把<Connector....>中加入URIEncoding="UTF-8",
然后在Servlet的doGet,doPost最前面加入:
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
但是在输出name变量时却是乱码,为什么?下面是我的代码:
//ServletUtils是输出Html的工具类,已包含//<meta http-equiv="Content-Type" content="text/html; charset=utf-8">public class GetParameterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); ServletUtilities util = new ServletUtilities(out); String name = request.getParameter("name"); String sex = request.getParameter("sex"); String content = "name: " + name + "<br>\n"; content += "sex: " + sex + "<br>\n"; content += "charset: " + request.getCharacterEncoding() + "<br>\n"; content += "<a href="?sex=我">next</a>"; String title = "Get parameter test"; util.print(title, content); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); }}