测试文件的放置:
1. post请求
在a.jsp中这么写
<form action="b.jsp" method="post">
userName: <input type="text" name="userName" />
<input type="submit" value="submit" />
</form>
在b.jsp中这么写
<% request.setCharacterEncoding("UTF-8");%>
<%= request.getParameter("userName")%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
效果图:
2. get请求
查看文档(进入http://localhost:8989/ , documentation->configuration->http)
可以看到
1)默认URI的编码方式是ISO-8859-1,我们可以利用new String()解码再编码,但是一个一个这么写太麻烦(不推荐)
a.jsp中这么写:
<form action="b.jsp" method="get">
userName: <input type="text" name="userName" />
<input type="submit" value="submit" />
</form>
b.jsp这么写:
<%
String val = request.getParameter("userName");
out.println(new String(val.getBytes("iso-8859-1") , "UTF-8"));
%>
效果图:
2)看useBodyEncodingForURI,设为true则指定解码方式和contentType指定的编码一致,但需要写request.setCharacterEncoding("UTF-8");(推荐)
我们需要修改映射文件Servers->tomcat v7.0->server.xml里面
还需要修改服务器端配置文件,tomcat7.0安装目录->conf->server.xml
都是改
<Connector connectionTimeout="20000" port="8989" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>
然后
a.jsp中这么写:
<form action="b.jsp" method="get">
userName: <input type="text" name="userName" />
<input type="submit" value="submit" />
</form>
b.jsp这么写:
<% request.setCharacterEncoding("UTF-8");%>
<%=request.getParameter("userName")%>
这时候,request.setCharacterEncoding("UTF-8")就对get请求有效
重启服务器即可
3)就是URIEncoding,但是要换编码需要在两个配置文件里面设置,没有第二种的灵活性(不推荐)
我们需要修改映射文件Servers->tomcat v7.0->server.xml里面
还需要修改服务器端配置文件,tomcat7.0安装目录->conf->server.xml
都是改
<Connector connectionTimeout="20000" port="8989" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
然后
a.jsp中这么写:
<form action="b.jsp" method="get">
userName: <input type="text" name="userName" />
<input type="submit" value="submit" />
</form>
b.jsp这么写:
<%=request.getParameter("userName")%>
重启服务器,效果一样: