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 */@Configurationpublic 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 locationsspring.mvc.static-path-pattern=/**spring.resources.static-locations=classpath:/web/static/,classpath:/web/libs/,classpath:/web/views/# VELOCITY TEMPLATES (VelocityAutoConfiguration)spring.velocity.charset=UTF-8spring.velocity.properties.input.encoding=UTF-8spring.velocity.properties.output.encoding=UTF-8spring.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;@Controllerpublic 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> <h3>姓名:${name}</h3> <h3>年齡:${age}</h3> </body></html>一段普通的HTML,只不過有name和age屬性需要渲染。那麼執行結果是什麼?啟動項目,輸入http://localhost:8080/index,展示頁面
可以看到是一個正常的HTML。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。