SpringBoot与velocity的结合的示例代码

Velocity是一种Java模版引擎技术,MVC架构的一种实现,但它更多的是关注在Model和View之间,作为它们的桥梁。服务端渲染,我们使用最多的就是用他来渲染HTML。下面我们看看他与spring boot的结合。

老样子,我们看下pom中定义的依赖

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-velocity</artifactId>
    </dependency>

spring-boot-starter-velocity 中定义了velocity模板需要的jar。

看下配置类中的配置

package com.shuqi;
import org.springframework.boot.autoconfigure.velocity.VelocityProperties;
import org.springframework.boot.web.servlet.view.velocity.EmbeddedVelocityViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author linyang
 * @date 2017/5/9
 */
@Configuration
public class WebConfig {

  @Bean
  public EmbeddedVelocityViewResolver velocityViewResolver(VelocityProperties properties) {
    EmbeddedVelocityViewResolver resolver = new EmbeddedVelocityViewResolver();
    properties.applyToViewResolver(resolver);
    resolver.setRedirectHttp10Compatible(false);
    return resolver;
  }
}

熟悉spring mvc 的同学都应该知道ViewResolver,是告诉spring mvc 怎样渲染这个视图,我们这边使用了VelocityViewResolver就是告诉spring mvc 使用Velocity的语法来渲染页面。但是仅有这个还不行,我们还有些配置文件的配置

# SpringBoot static resources locations
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/web/static/,classpath:/web/libs/,classpath:/web/views/

# VELOCITY TEMPLATES (VelocityAutoConfiguration)
spring.velocity.charset=UTF-8
spring.velocity.properties.input.encoding=UTF-8
spring.velocity.properties.output.encoding=UTF-8
spring.velocity.resourceLoaderPath=classpath:/web/views/
spring.velocity.suffix=.vm

里面配置了velocity模板的后缀是.vm,编码统一使用UTF-8,视图的加载位置,静态资源的加载位置等。说白了,就是告诉spring mvc,我们的资源文件放到什么位置,然后才能取到,才能渲染。

配置搞定后,我们看下业务代码

package com.shuqi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@Controller
public class HelloController {
  @RequestMapping(value = "/index", method = RequestMethod.GET)
  public ModelAndView index() {
    Map<String, String> map = new HashMap<>();
    map.put("name", "shuqi");
    map.put("age", "26");
    return new ModelAndView("index", map);
  }
}

设置了name与age的值,设置了需要渲染文件的位置及名称。含义就是:用map中的值,渲染index这个文件。我们最后看一眼,index这个文件的内容

<html>
  <body>
   <h4>姓名:${name}</h4>
   <h4>年龄:${age}</h4>
  </body>
</html>

一段普通的HTML,只不过有name和age属性需要渲染。那么执行结果是什么?启动项目,输入http://localhost:8080/index,展示页面

SpringBoot与velocity的结合的示例代码

可以看到是一个正常的HTML。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。