java mvc引擎_Velocity是一种Java模版引擎技术,MVC架构的一种实现,但它更多的是关注在Model和View之间,作为它们的桥梁。服务端渲染,我们使用最多的就是用他...
Velocity是一種Java模版引擎技術,MVC架構的一種實現,但它更多的是關注在Model和View之間,作為它們的橋梁。服務端渲染,我們使用最多的就是用他來渲染HTML。下面我們看看他與spring boot的結合。
老樣子,我們看下pom中定義的依賴
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這個文件的內容
姓名:${name}
年齡:${age}
一段普通的HTML,只不過有name和age屬性需要渲染。那么執行結果是什么?啟動項目,輸入http://localhost:8080/index,展示頁面
可以看到是一個正常的HTML。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
總結
以上是生活随笔為你收集整理的java mvc引擎_Velocity是一种Java模版引擎技术,MVC架构的一种实现,但它更多的是关注在Model和View之间,作为它们的桥梁。服务端渲染,我们使用最多的就是用他...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魅族 20 Pro样机疑似曝光 或搭载F
- 下一篇: 1km收费2元多!日本高速公路收费政策再