淘宝商城(天猫)高级技术专家.3年研发+3年性能测试调优/系统测试+4年团队管理与测试架构、研发系统实践. 新舞台新气象, 深化测试基础架构及研发架构,希望能在某个技术领域成为真正的技术大牛。欢迎荐才http://bbs.51testing.com/viewthread.php?tid=120496&extra=&page=1 .邮件: jianzhao.liangjz@alibaba-inc.com,MSN:liangjianzhao@163.com.微博:http://t.sina.com.cn/1674816524

Spring+mysql+velocity 中文问题解决方法

上一篇 / 下一篇  2008-09-23 13:11:20 / 个人分类:java性能监控与调优

碰到中文问题主要有几类:

1)     confluencemysql数据库导出的UTF-8数据

2)     http get/post请求中汉字

3)     ajax xmlhttprequest传递的汉字

4)     mysql环境设置

5)     spring /velocity /jboss环境的中文配置

 

成功的文件配置关键内容如下:

1.1      spring2应用Web.xml配置

 

<filter>

             <filter-name>encodingFilter</filter-name>

             <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

             <init-param>

                    <param-name>encoding</param-name>

                    <param-value>GB2312</param-value>

             </init-param>

             

             <init-param>

           <param-name>forceEncoding</param-name>

           <param-value>true</param-value>

   </init-param>

 

      </filter>

 

 

1.2      Ibatis sqlmap-config.xml

 

<?xml version="1.0" encoding="UTF-8" ?>

 

 

1.3      ibatis jdbc配置:

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/scmproj?useUnicode=true&characterEncoding=UTF-8

 

 

 

 

1.4      spring mvc:

 

      <bean id="velocityConfigurer"                        class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">

             <property name="resourceLoaderPath">

             <value>WEB-INF/velocity/</value>  

             </property>

             <property name="velocityProperties">

                    <props>

                   <prop key="input.encoding">GB2312</prop>

                    <prop key="output.encoding">GB2312</prop>

                    <prop key="contentType">text/html;charset=GB2312</prop>

                    <prop key="file.resource.loader.cache">false</prop>

                    <prop key="file.resource.loader.modificationCheckInterval">1</prop>

                    <prop key="velocimacro.library.autoreload">true</prop>

                    <prop key="velocimacro.library">templates.vm</prop>

                    <prop key="runtime.log.logsystem.class">org.apache.velocity.runtime.log.SimpleLog4JLogSystem</prop>

                    <prop key="runtime.log">com.ali</prop>

                    <prop key="runtime.log.error.stacktrace">true</prop>

                    <prop key="runtime.log.warn.stacktrace">true</prop>

                    <prop key="runtime.log.info.stacktrace">false</prop>

                    <prop key="runtime.log.invalid.reference">true</prop>                        

             </props>

             </property>

 

      </bean>

      

       <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">

         <property name="suffix"><value>.vm</value></property>

                    <property name="exposeSpringMacroHelpers"><value>true</value></property>

                    <property name="exposeRequestAttributes"><value>true</value></property>

                    <property name="exposeSessionAttributes"><value>true</value></property>

                    <property name="contentType" value="text/html;charset=UTF-8" />

                    <property name="dateToolAttribute">

     <value>dateTool</value>

         </property>

       </bean>

      

 

由于页面上文字是汉字,但数据库为utf-8VelocityViewResolvercontentType必须为UTF-8 ,否则部分复杂汉字无法正常显示。如璟。

 

 

1.5      Mysql5.0创建数据库:

create database scmproj DEFAULT CHARACTER SET utf8;

 

1.6      mysql的配置文件my.ini

[mysql]

 

default-character-set=gb2312

[mysqld]

default-character-set=utf8

 

1.7      velocity页面

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@page pageEncoding="gb2312"%>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html;charset=gb2312" />

 

 

1.8      velocity表单提交前编码

 

<scrīpt language="vbscrīpt">

 

Function GetByteCode(ch)  

 

   code = Asc(ch)         ' -20001

 

   GetByteCode = Hex(code) ' "B1DF"

 

End Function

 

</scrīpt>

 

 

<scrīpt language="javascrīpt">

 

String.prototype.urlEncode = function() {

 

   var r = "";

 

   for (var i = 0; i < this.length; i++) {

 

       var code = "" + GetByteCode(this.charAt(i));

 

       if (code.length > 2) {

 

           var b1 = code.substr(0, code.length - 2);

 

           var b2 = code.substr(code.length - 2);

 

           if (i == 0) {

 

               //alert("" + code + ", " + b1 + ", " + code.length + ", " + b2);

 

           }

 

           r += "%" + b1 + "%" + b2;

 

       } else {

 

           r += "%" + code;

       }

   }

   return r;

}

 

</scrīpt>

 

 

Function checkform()

{

 

var ōldvalue= document.formtips.content.value;

             if(oldvalue=="")

             {

                    alert("请设置值");

                    return false;

             }

             var urlEncodeResult=oldvalue.urlEncode();

             

             document.formtips.content.value=urlEncodeResult;   

}

 

1.9      接收form表单的服务器端JAVA代码

 

protected ModelAndView onSubmit(HttpServletRequest request,

                    HttpServletResponse response, Object command, BindException errors)

                    throws Exception {

 

             try {

                    SCMTips tips = (SCMTips) command;

                    

                    if (logger.isInfoEnabled()) {

                           logger.info("before decode content:" + tips.getContent());

                           logger.info("requestEncode="+ request.getCharacterEncoding());

                    }

 

                   String decoderesult = java.net.URLDecoder.decode(tips.getContent(),

                                  "gb2312");

 

                    if (logger.isInfoEnabled()) {

                           logger.info("decode result:" + decoderesult);

                    }

 

1.10 AJAX发送端

 

function makeHttpReq()

 {

    var new_httpreq = null;

    if (window.XMLHttpRequest) {

              new_httpreq = new XMLHttpRequest();

              if (new_httpreq.overrideMimeType){

               new_httpreq.overrideMimeType('text/xml');

              }

              } else if (window.ActiveXObject) {

              try{

               new_httpreq = new ActiveXObject("Msxml2.XMLHTTP");

              } catch (e) {

               try {

                new_httpreq = new ActiveXObject("Microsoft.XMLHTTP");

               } catch (e) {

               }

              }

              }

             return new_httpreq;

 }

 

 

     if (httpReq)  {  
          httpReq.onreadystatechange  =  function(){
            if(httpReq.readyState == 4)
            {
             //var console=document.getElementById('console'); 
             //alert(httpReq.responseText);
             //console.innerHtml = httpReq.responseText;
             }
       };
          
          httpReq.open("GET",   url,   true);  
          httpReq.setRequestHeader("If-Modified-Since","0");
          httpReq.send(null);  
      }    
  

从上面可以看到httqreq没有指定编码格式。默认就是ISO-8859-1。

2.11 接收ajax处理的服务器端代码
public ModelAndView handleRequestInternal(HttpServletRequest request,
   HttpServletResponse response) throws Exception {

  if (request.getMethod().equals("GET")) {
   String encodeProj = request.getParameter("projectname");
   if (logger.isInfoEnabled()) {
    logger.info("before decode:" + encodeProj);
   }
   //客户端经过编码后的汉字   
   String projectname= new String( encodeProj.getBytes( "8859_1" ) , "gb2312" );
   if (logger.isInfoEnabled()) {
    logger.info("after decode:" + projectname);
   }


2.12 JBOSS4.2配置
D:\jboss-4.2.2.GA\server\default\deploy\jboss-web.deployer \Server.xml 里面
    -->
    <Connector port="8080" address="${jboss.bind.address}"   
         maxThreads="250" maxHttpHeaderSize="8192"
         emptySessionPath="true" protocol="HTTP/1.1"
         enableLookups="false" redirectPort="8443" acceptCount="100"
         connectionTimeout="20000" disableUploadTimeout="true"  />

没有修改URIEncoding

 

 


TAG: 编码 java性能监控与调优 MySQL Spring 中文 解决 velocity 乱码

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar