Spring MVC整合Velocity详解


一、Velocity简介

Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。

当Velocity应用于web开发时,界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人 员可以只关注页面的显示效果,而由java程序开发人员关注业务逻辑编码。Velocity将java代码从web页面中分离出来,这样为web站点的长 期维护提供了便利,同时也为我们在JSP和PHP之外又提供了一种可选的方案。

Velocity现在应用非常广泛,以下将详细讲解SpringMVC项目与Velocity整合。

二、SpringMvc+Velocity整合

主要涉及以下文件

pom.xml(引入velocity的jar包)

spring-mvc.xml(视图配置,配置velocity)

velocity.properties(velocity配置文件)

1、引入jar包

引入相关依赖的jar包,主要包含 velocity-1.7.jar和velocity-tools-2.0.jar包

<!-- Velocity模板 -->

<dependency>

  <groupId>org.apache.velocity</groupId>

  <artifactId>velocity</artifactId>

  <version>1.7</version>

</dependency>

<dependency>

  <groupId>velocity-tools</groupId>

  <artifactId>velocity-tools-generic</artifactId>

  <version>2.0</version>

</dependency>

2、 视图配置

<!-- 视图模式配置,velocity配置文件 -->

<beanid="velocityConfig"class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">

  <propertyname="resourceLoaderPath"value="/WEB-INF/vm"/>

  <propertyname="configLocation"value="classpath:velocity.properties"/>

</bean>

<!-- 配置后缀 -->

<beanid="velocityViewResolver"class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">

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

  <propertyname="suffix"value=".vm"/>

</bean>


3、配置velocity.properties文件

#encoding

input.encoding=UTF-8

output.encoding=UTF-8

#autoreload when vm changed

file.resource.loader.cache=false

file.resource.loader.modificationCheckInterval=2

velocimacro.library.autoreload=false

4、编写velocity页面

配置完后,写一个vm页面展示key的页面myVelocity.vm,该页面的路径在:WEB-INF/vm下

<!DOCTYPEhtml>

<htmllang="en">

<head>

<metacharset="UTF-8">

<title>show all users</title>

</head>

<body>

<table>

  $!{key}

</table>

</body>

</html>

5、编写控制层

起名为VelocityController.java

package com.xxx.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.alifi.uums.mv.JModelAndView;

@Controller

@RequestMapping("/test/velocity")

publicclass VelocityController {

  @RequestMapping({"/myVelocity.do" })

  public ModelAndView test(HttpServletRequest request) {

 ModelAndView mv =new JModelAndView("myVelocity", request, true);

 mv.addObject("key","我来了,velocity!");

 return mv;

  }

}


6、测试结果

访问地址

http://localhost:8080/mypoject/test/velocity/myVelocity.do

页面上展示的内容为:我来了,velocity!



猜你喜欢

转载自blog.csdn.net/tjcyjd/article/details/78495504
今日推荐