问题描述
===index.jsp===<%@pagelanguage="java"pageEncoding="gbk"contentType="text/html;charset=gbk"%><html><body> <formmethod="post"action="codeTest.action"> 输入中文:<inputtype="text"name="str"><br> <inputtype="submit"value="submit"> </form> </body></html>
===CodeTestAction.java===packageaction;importorg.apache.struts2.ServletActionContext;importcom.opensymphony.xwork2.ActionSupport;publicclassCodeTestActionextendsActionSupport{ privateStringstr; publicStringgetStr() { returnstr; } publicvoidsetStr(Stringstr) { this.str=str; } publicStringexecute()throwsException { System.out.println(str); System.out.println(ServletActionContext.getRequest().getCharacterEncoding()); System.out.println(newString(str.getBytes("utf-8"),"gbk")); returnSUCCESS; }}
===struts.xml===<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEstrutsPUBLIC "-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"><struts> <constantname="struts.i18n.encoding"value="utf-8"/> <packagename="struts2"extends="struts-default"> <actionname="codeTest"class="action.CodeTestAction"> <result>/index.jsp</result> </action> </package> </struts>
启动服务器,访问index.jsp。填上中文提交。控制台输出????UTF-8锟斤拷锟斤拷我的理解:index.jsp用的gbk,用户提交的str是gbk的编码。struts.i18n.encoding是utf-8,所以在CodeTestAction中得到的str是用utf-8解释的乱码。所以用str.getBytes("utf-8")得到用户原本提交的字节码,然后恢复成gbkSystem.out.println(newString(str.getBytes("utf-8"),"gbk"));可为什么打印出的还是乱码呢?我哪里理解错了?少了什么环节么?(我知道,统一编码就能解决。可是我想透彻的理解这个地方。请大家帮忙看看)