SpringBoot与velocity的结合的示例代码

网友投稿 425 2023-02-11


SpringBoot与velocity的结合的示例代码

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

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

<groupId>org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-velocity

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 map = new HashMap<>();

map.put("name", "shuqi");

map.put("age", "26");

return new ModelAndView("index", map);

}

}

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

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

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Angular学习笔记之集成三方UI框架、控件的示例
下一篇:游戏接口测试(游戏接口测试 数据格式)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~