form表单使用get方法输入中文:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<form action="http://localhost:8080/SecondProj/servlet/HelloForm" method="GET" >
名字:<input type="text" name="first_name" >
<br />
姓氏:<input type="text" name="last_name" />
<input type="submit" value="提交" />
</form>
</body>
</html>
然后使用servlet的doGet方法获取输入值:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html");
// response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String title = "使用 GET 方法读取表单数据";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 "
+ "transitional//en\">\n";
out.println(docType + "<html>\n" + "<head><title>" + title
+ "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n"
+ "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n"
+ " <li><b>名字</b>:" + request.getParameter("first_name")
+ "\n" + " <li><b>姓氏</b>:" + request.getParameter("last_name")
+ "\n" + "</ul>\n" + "</body></html>");
}
点击提交显示的页面输入的内容是乱码,只有输入的内容是乱码!
百度了好多,有的说是jsp的page-encoding要设置成utf-8,有的说是request.setContentType(“text/html;charset=utf-8”),还有的说是修改Tomcat的conf文件夹里的server.xml文件里面的<Connector>标签的URIEncoding=“UTF-8”,结果都不管用。
后来看到说是修改Tomcat的conf文件夹里的server.xml文件里面的<Connector>标签的URIEncoding=“GBK”,我当时想的是,utf-8就支持汉字,也不管用,换成gbk就行了?根本没去试,隔了一天实在没辙了就去试了,bingo!成了哎,unbelievable!
但是我还是不清楚为什么utf-8格式不行...
我知道了,右键查看页面信息可以看到页面的文字编码是gbk,所以要转成gbk格式的!
2017-3-24更新:其实,String str = request.getParameter(“name值”);之后,String newStr = new String(str.getBytes("ISO-8859-1"),"GBK")就行了。