美文网首页sspringmvc
SpringMVC整合jsp与velocity

SpringMVC整合jsp与velocity

作者: 骄傲牛 | 来源:发表于2016-02-05 14:09 被阅读0次

本来的项目是纯SpringMVC的,没办法,只会java。后来觉得是不是可以用其它东西来替换jsp,然后发现velocity的东西。

velocity是一种模板语言,与它类似的还有freemark。veocity的优点的快,缺点的功能不算特别强大;freemark的功能超级强大,但速度慢一些。我偏向使用简洁快速的velocity,另外velocity的layout功能也是我决定用它来替换jsp的一个原因。

整合多视图

原来还用着的jsp不可能马上就干掉,所以需要在SpringMVC里配置多个视图解析器(ViewResolver)

好在SpringMVC本身就支持多个视图的配置,原来的配置如下:

<!--jsp视图解析器-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

现在要增加一个velocity视图解析器,增加一个VelocityLayoutViewResolver的,同时要注意order参数的配置。SpringMVC不知道每个解析器的调用顺序,需要我们自己在配置时就配置好:

    <!--jsp视图解析器-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="order" value="1"/>
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- velocity视图解析器 -->
    <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="order" value="0"/>
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="cache" value="true"/>
        <property name="prefix" value="/"/>
        <property name="layoutUrl" value="layout/default.vm"/>
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="dateToolAttribute" value="dateTool"/>
        <property name="numberToolAttribute" value="numberTool"/>
    </bean>

因为要兼容原来的jsp视图,所以我将jsp配置成了优先级最高。对于velocity还要增加一些配置,以下是velocity必须要有的配置

    <!-- velocity环境配置 -->
    <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <!-- velocity配置文件路径 -->
        <property name="configLocation" value="/WEB-INF/velocity.properties"/>
        <!-- velocity模板路径 -->
        <property name="resourceLoaderPath" value="/WEB-INF/vm/"/>
    </bean>

以及velocity.properties的配置

#设置字符集
input.encoding=UTF-8
output.encoding=UTF-8

velocity的layout用法

如果只是简单的把jsp文件改成用vm文件来写就没有什么意思了,layout是一个比较有意思的用法,它可以将大量公共的页面框架写成一个独立的文件,让最终的视图文件去引用。即可以大量简化代码,又可以让程序员专注与当前的页面逻辑。

模板文件如下:

## file=template.vm
<html>
<head>
  <title>$!page_title</title>
</head>
<body>
  $screen_content
</body>
</html>

业务文件代码如下:

#set( $layout = "template.vm" )
#set( $page_title = "this is the test page")
#define($screen_content)
    this is buisin content
#end

看多简单!

相关文章

网友评论

    本文标题:SpringMVC整合jsp与velocity

    本文链接:https://www.haomeiwen.com/subject/tfzekttx.html