zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

Spring集成Velocity的中文解决方案

2023-02-18 15:31:11 时间

在Spring framework中使用Velocity是非常方便的,只需在spring配置文件中申明:

<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配置文件中设置:

<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,但是不利于多语言移植。