日期:2014-05-16  浏览次数:20660 次

Tomcat6服务器编码及Ajax中文乱码问题

Tomcat6服务器编码为引用其他人的内容连接地址为:http://guozheng.iteye.com/blog/681207

偶然遇到这个问题,utf-8编码格式用tomcat-6.0.18部署之后页面显示全是乱码。

解决方法:

???? 配置tomcat的server.xml? 在下面两个地方加:URIEncoding="UTF-8"

?

???? <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000"redirectPort="8443"??

? ???????? URIEncoding="UTF-8" />

  <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"?

????????? URIEncoding="UTF-8"/>

?

如果还是不行,可以在上面修改的基础上? 从? tomcat 的自带项目? Examples是里的---\webapps\examples\WEB-INF\classes\filters

下找到?? RequestDumperFilter.java?? 和?? SetCharacterEncodingFilter.java,

?加入到工程文件中去。

并把这个tomcat带的编码过滤器配置到web.xml里

?? <filter>
    <filter-name>Set Character Encoding</filter-name>
      <filter-class>xxx.xxx.xxx.SetCharacterEncodingFilter</filter-class>

?????????????????? <!--类路径-->
      <init-param>
        <param-name>encoding</param-name>
        <param-value>GBK</param-value>
      </init-param>
    </filter>
    <filter-mapping>
      <filter-name>Set Character Encoding</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

?

?

Ajax中文乱码问题

在页面中用如下方式解决:

??? var reportTmpId = $("#reportTmpId").val();
????var attrKey = encodeURI(encodeURI($("#attrKey").val()));
????$.post("${ctp}/ms/report/validateKeyRepTmpAttr.action?reportTmpId="+reportTmpId+"&attrKey="+attrKey,null,function(flag){???
????? ????if(flag=="false"){
???????? ? ???document.all("keyMsg").style.color="green";
??? ?? ????document.all("keyMsg").innerHTML="可以使用";
??????? ???}else{
????????? ????document.all("keyMsg").style.color="red";
??? ?? ????document.all("keyMsg").innerHTML="名字重复!";
???????? ???}
????? ???});

在Action类中:

?public String validateName(){
??? ?logger.debug("进入ReportTemplateAction的validateName方法!");
??? ?String reportName = null;
???? try{
??????? reportName = URLDecoder.decode(request.getParameter("reportName"),"utf-8");
??????? if(reportName != null && !"".equals(reportName)){
??????????? TReportTemplate tmp = this.reportTemplateMngImpl.validateName(reportName);
??????????? if(tmp == null){
??????????????? response.getWriter().print("false");
??????????? }else{
??????????????? response.getWriter().print("true");
??????????? }
??????? }
??}catch(Exception e){
??????? e.printStackTrace();
??????? logger.error("执行ReportTemplateAction的validateName方法出现异常!"+e.getMessage());
??}
??return null;
?}