天天看點

Spring MVC整合Velocity詳解一、Velocity簡介二、SpringMvc+Velocity整合

Spring MVC整合Velocity詳解一、Velocity簡介二、SpringMvc+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!

Spring MVC整合Velocity詳解一、Velocity簡介二、SpringMvc+Velocity整合

繼續閱讀