JSP的中文乱码问题,有时好不容易看懂了,隔断时间不用又忘了,先写在这里,便于日后查看。
先确保页面中文显示正常,先确定将所有的html,jsp文件都用UTF-8保存(可以打开记事本,File | Save as 查看文件的编码格式)
Introspection.html
Introspection.jsp
SimpleBean.java
Url中取得的参数(get)编码设置
1) Tomcat安装路径conf/server.xml中加入URIEncoding="UTF-8"
<Connector port="8080"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true" URIEncoding="UTF-8" />
<Connector port="8009"
enableLookups="false" redirectPort="8443" protocol="AJP/1.3" URIEncoding="UTF-8" />
2)
action="Introspection.jsp?hometown=<%=URLEncoder.encode("湖北","UTF-8")%>"
解码时直接用
java.net.URLDecoder.decode(request.getParameter("hometown"));
附: 汉字和UTF-8编码之间转换的js代码
<table>
<tr>
<td height="30" align="center">请将您要<b style="color:red; background-color:#cccccc">转换</b>的汉文复制到下框</td>
</tr>
<tr>
<td height="30" align="center"><textarea id="code" name="code" cols="60" rows="5"></textarea></td>
</tr>
<tr>
<td height="30" align="center"><input type="button" onclick="encode(code,this)" value=" 转 化 "></td>
</tr>
</table>
<script>
var mode="encode";
function encode(obj,btn){
if(mode=="encode"){
obj.value=obj.value.replace(/[^/u0000-/u00FF]/g, function($0){return escape($0).replace(/(%u)(/w{4})/gi,"&#x$2;")});
btn.value=" 还 原 ";
mode="decode";
}else{
obj.value=unescape(obj.value.replace(/&#x/g,'%u').replace(/;/g,''));
btn.value=" 转 化 ";
mode="encode";
}
}
</script>