`

92.Spring Boot使用模板velocity【从零开始学Spring Boot】

阅读更多

 

 à悟空学院:https://t.cn/Rg3fKJD

学院中有Spring Boot相关的课程!点击「阅读原文」进行查看!

SpringBoot视频:http://t.cn/A6ZagYTi

Spring Cloud视频:http://t.cn/A6ZagxSR

SpringBoot Shiro视频:http://t.cn/A6Zag7IV

SpringBoot交流平台:https://t.cn/R3QDhU0

SpringData和JPA视频:http://t.cn/A6Zad1OH

SpringSecurity5.0视频:http://t.cn/A6ZadMBe

Sharding-JDBC分库分表实战http://t.cn/A6ZarrqS

分布式事务解决方案「手写代码」:http://t.cn/A6ZaBnIr

 

【原创文章,转载请注明出处,提供源代码下载】

 

      在写此博客之前,我要对通过支付宝,微信公众号,微信给我的文章打赏的小伙伴表示感谢,谢谢你们的支持,虽然money不多,但是确实是对我很大的鼓励,谢谢你们,有你们的支持,我相信我的博客质量也会越来越好。

     好了,说了一些题外话,我们还是进入正题吧。距离上一篇博客,又过了10天了,今天我们讲讲怎么在Spring Boot中使用模板引擎velocity,先看看今天的大纲:

  

(1) velocity介绍;
(2) 新建spring-boot-velocity工程;
(3) 在pom.xml引入相关依赖;
(4) 编写启动类;
(5) 编写模板文件hello.vm;
(6) 编写访问类HelloController;
(7) 测试;
(8) velocity配置;
(9) velocity常用语法;
(10) velocity layout

 

 (1) velocity介绍;

 

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

       官网:http://velocity.apache.org/

       模板引擎的使用我们其中的一个章节中介绍过freemarkerthymeleaf的使用。

 

 

 (2) 新建spring-boot-velocity工程;

       我们新建一个maven工程,取名为:spring-boot-velocity

 

 

(3) pom.xml引入相关依赖;

 

       在这里需要说明下,其一就是之后的博客应该会直接使用1.4.1的版本作为讲解了,其二就是在这里使用velocity需要引入相关依赖包:spring-boot-starter-velocity

 

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.kfit</groupId>
  <artifactId>spring-boot-velocity</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-boot-velocity</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <!-- jdk版本号,angel在这里使用1.8,大家修改为大家本地配置的jdk版本号即可 -->
    <java.version>1.8</java.version>
  </properties>
  
    <!-- 
		spring boot 父节点依赖,
		引入这个之后相关的引入就不需要添加version配置,
		spring boot会自动选择最合适的版本进行添加。
	 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.1.RELEASE</version><!-- 1.4.1.RELEASE , 1.3.3.RELEASE-->
	</parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    
        <!-- spring boot web支持:mvc,aop... -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
    
    <!-- 引入velocity的依赖包. -->
    <dependency>    
	    <groupId>org.springframework.boot</groupId>   
	    <artifactId>spring-boot-starter-velocity</artifactId>
	</dependency>
    
  </dependencies>
</project>

 

 

(4) 编写启动类;

 

       启动类没有什么特别之处,不过多介绍,请看代码:

 

package com.kfit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 
 * @author Angel -- 守护天使
 * @version v.0.1
 * @date 2016年10月4日
 */
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

 

 

 

(5) 编写模板文件hello.vm;

  编写一个hello.vm文件,此文件的路径在src/main/resources下,其中hello.vm文件的内容如下:

 

<html>  
<body>  
	welcome ${name}  to velocity!
</body>  
</html>

 

 

(6) 编写访问类HelloController;

 

有了模板文件之后,我们需要有个Controller控制类,能够访问到hello.vm文件,这里也很简单,具体看如下代码:

 

package com.kfit.demo.web;

import java.util.Map;

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

/**
 * 测试velocity;
 * @author Angel -- 守护天使
 * @version v.0.1
 * @date 2016年10月4日
 */
@Controller
public class HelloController {
	
	@RequestMapping("/hello")
	public String hello(Map<String,Object> map){
		map.put("name", "[Angel -- 守护天使]");
		return "hello";
	}
	
}

 

 

(7) 测试;

       好了,到这里,我们就可以启动我们的程序进行测试了,访问地址:

http://127.0.0.1:8080/hello ,如果你在浏览器中看到如下信息:

welcome [Angel -- 守护天使] to velocity!

 

那么说明你的demo ok 了。

 

(8) velocity配置;

       spring bootapplication.properties属性文件中为velocity提供了一些常用的配置,如下:

 

spring.velocity.allow-request-override=false # Set whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name.

spring.velocity.allow-session-override=false # Set whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name.

spring.velocity.cache= # Enable template caching.

spring.velocity.charset=UTF-8 # Template encoding.

spring.velocity.check-template-location=true # Check that the templates location exists.

spring.velocity.content-type=text/html # Content-Type value.

spring.velocity.date-tool-attribute= # Name of the DateTool helper object to expose in the Velocity context of the view.

spring.velocity.enabled=true # Enable MVC view resolution for this technology.

spring.velocity.expose-request-attributes=false # Set whether all request attributes should be added to the model prior to merging with the template.

spring.velocity.expose-session-attributes=false # Set whether all HttpSession attributes should be added to the model prior to merging with the template.

spring.velocity.expose-spring-macro-helpers=true # Set whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext".

spring.velocity.number-tool-attribute= # Name of the NumberTool helper object to expose in the Velocity context of the view.

spring.velocity.prefer-file-system-access=true # Prefer file system access for template loading. File system access enables hot detection of template changes.

spring.velocity.prefix= # Prefix that gets prepended to view names when building a URL.

spring.velocity.properties.*= # Additional velocity properties.

spring.velocity.request-context-attribute= # Name of the RequestContext attribute for all views.

spring.velocity.resource-loader-path=classpath:/templates/ # Template path.

spring.velocity.suffix=.vm # Suffix that gets appended to view names when building a URL.

spring.velocity.toolbox-config-location= # Velocity Toolbox config location. For instance `/WEB-INF/toolbox.xml`

spring.velocity.view-names= # White list of view names that can be resolved.     

 


(9) velocity常用语法;

 

Velocity的语法并不是本节的重点,这里还是简单的介绍下几个常用的if else,foreach

 

       首先我们改造下HelloControllerhello方法

 

 

@RequestMapping("/hello")
	public String hello(Map<String,Object> map){
		map.put("name", "[Angel -- 守护天使]");
		map.put("gender","1");//gender:性别,1:男;0:女;
		
		List<Map<String,Object>> friends =new ArrayList<Map<String,Object>>();
		Map<String,Object> friend = new HashMap<String,Object>();
		friend.put("name", "张三");
		friend.put("age", 20);
		friends.add(friend);
		friend = new HashMap<String,Object>();
		friend.put("name", "李四");
		friend.put("age", 22);
		friends.add(friend);
		map.put("friends", friends);
		return "hello";
	}

 

 

       这里我们返回了genderfriends的列表;

 

     接下来我们看看怎么在velocity进行展示呢?

<html>  
<body>  
	welcome ${name}  to velocity!
	<p>性别:
		#if($gender == 1) 
			男
		#elseif($gender == 0)
			女
		#else 
			保密
		#end
	 </p>
	<h4>我的好友:</h4>	
		
		#foreach( $info in $friends )
			姓名:$info.name , 年龄$info.age
			<br/>
		#end
	
</body>  
</html>

 

 

(10) velocity layout

 

Velocity layout主要处理具有相同内容的页面,比如每个网站的headerfooter页面。

 

   Velocity的布局主要常见的两种方式是#parse(“文件路径”)#include(“文件路径”),其中paseinclude的区别在于,若包含的文件中有velocity监本标签,parse将会进一步解析,而include将原样显示。

 

  

 

       我们编写一个headerfooter,其中的header使用parse引入,footer页面使用include引入。

       header.vm内容:

 

<header>
	This is a header,welcome  $name to my web site!
</header>
	
<hr>

 

 

 

       footer.vm内容:

<hr>
<footer>
	This is a footer,welcome  $name to my web site!
</footer>

        修改hello.vm

 

 

 

<html>  
<body>  
	
	#parse("/header.vm")

	welcome ${name}  to velocity!
	<p>性别:
		#if($gender == 1) 
			男
		#elseif($gender == 0)
			女
		#else 
			保密
		#end
	 </p>

	<h4>我的好友:</h4>	
		
		#foreach( $info in $friends )
			姓名:$info.name , 年龄$info.age
			<br/>
		#end
		
	#include("/footer.vm")
	
</body>  
</html>

        到这里就ok了,我们访问/hello页面,应该会看到如下图的效果:

 

 

 

好了,到这里spring boot使用velocity就介绍到这里了,对于velocity的语法大家可以看看别的博客或者直接上官网看看。

 

à悟空学院:https://t.cn/Rg3fKJD

学院中有Spring Boot相关的课程!点击「阅读原文」进行查看!

SpringBoot视频:http://t.cn/A6ZagYTi

Spring Cloud视频:http://t.cn/A6ZagxSR

SpringBoot Shiro视频:http://t.cn/A6Zag7IV

SpringBoot交流平台:https://t.cn/R3QDhU0

SpringData和JPA视频:http://t.cn/A6Zad1OH

SpringSecurity5.0视频:http://t.cn/A6ZadMBe

Sharding-JDBC分库分表实战http://t.cn/A6ZarrqS

分布式事务解决方案「手写代码」:http://t.cn/A6ZaBnIr

 

 

  • 大小: 35 KB
分享到:
评论
3 楼 hong199275 2017-04-24  
好像spring boot 1.5.x后面默认不支持velocity 啦?不得不说,spring boot 更新的有点小快
2 楼 林祥纤 2016-10-09  
graying 写道
写得不错哦,加油!


Thx.
1 楼 graying 2016-10-08  
写得不错哦,加油!

相关推荐

Global site tag (gtag.js) - Google Analytics