Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux資訊 >> 更多Linux

解決Spring Framework集成Velocity的中文亂碼問題

在Spring Framework中使用Velocity非常方便,只需在Spring配置文件中聲明VelocityViewResolver:

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

之後便可在Spring MVC框架中直接返回new ModelAndView("velocity模板", map)。但中文一直是亂碼。

解決中文亂碼

考慮到國際化,先把所有Web頁面統一用UTF-8編碼,接著在/WEB-INF/velocity.properties文件中覆蓋Velocity的默認編碼ISO-8859-1:

input.encoding = UTF-8
output.encoding = UTF-8

最後在Spring配置文件中設置contentType:

<bean id="viewResolver"
 class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
 <property name="contentType">
  <value>text/html;charset=UTF-8</value>
 </property>
</bean>

重啟Web服務器後,中文顯示與輸入便都正常了。你也可以改用GBK,但它不利於多語言移植。

附:Velocity簡介

Velocity是Apache的開源項目,實現了可替代JSP的View層,並以直觀的方式編寫視圖。編寫一個Velocity View就像編寫純HTML文件,完全可以在Dreamweaver中可視化編寫,只需把數據部分用$xxx替換。例如顯示用戶信息時,Model傳入一個包含username、email、address三個Key的Map:

<html>
<title>User: $username</title>
<body>
 <p>Email: $email</p>
 <p>Address: $address</p>
</body>
</html>

這樣就完全不必擔心嵌套的JSP標簽在Dreamweaver中造成語法錯誤了。

Copyright © Linux教程網 All Rights Reserved