项目地址:https://github.com/zhaopeng01/springboot-study/tree/master/study8
Spring Boot提供了多种模板引擎的默认配置支持,但嵌入式容器JSP有限制,2010年后Velocity停止更新,所以这JSP与Velocity两个不建议使用,然实际在企业中,还是有很多在使用
那么这里主要是
springboot
整合Thymeleaf
模板。
在SpringBoot
使用上述模板,默认从src/main/resources/templates
下加载。
Thymeleaf
是现代化服务器端的Java模板引擎,不同与其它几种模板的是Thymeleaf的语法更加接近HTML,并且具有很高的扩展性,其他详细可移步官网
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
先创建一个实体类
entity
package com.zyc.entity;
public class Person {
private String name;
private String gender;
private String email;
//get set 方法
}
创建一个controller 用来映射HTTP请求与页面的跳转
controller
package com.zyc.controller;
import com.zyc.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* @Description: Thymeleaf
* @author zhaopeng
* @email zp152527@163.com
*/
@Controller
@RequestMapping
public class ThyController {
@GetMapping("/index")
public ModelAndView index() {
ModelAndView view = new ModelAndView();
view.setViewName("index");
// 设置属性
view.addObject("title", "Thymeleaf页面");
view.addObject("desc", "Welcome to Thymeleaf");
Person person = new Person();
person.setGender("男娃子");
person.setEmail("77742344@qq.com");
person.setName("赵鹏");
view.addObject("person", person);
return view;
}
@GetMapping("/index1")
public String index1(HttpServletRequest request) {
// 设置属性
request.setAttribute("title", "Thymeleaf页面");
request.setAttribute("desc", "Welcome to Thymeleaf");
Person person = new Person();
person.setGender("难道到这里就能变成个女娃子?");
person.setEmail("77742344@qq.com");
person.setName("赵鹏");
request.setAttribute("person", person);
return "index";
}
}
两个方法的写法不同,但是结果一致。
在第一个方法中设置的跳转到index,默认映射到 src/main/resources/templates/{viewName}.html
在第一个方法中设置的跳转到index,默认映射到 src/main/resources/templates/xxxx.html
这样就基本ok了,可以先直接将这个index.html打开看一下,这是静态效果
然后运行我们的项目,访问 http://localhost:8080/index 然后可以看到我们的动态效果
了
SpringBoot
默认情况下为我们做了如下的默认配置工作,当然我们也可以在自己需要的情况下去修改这些配置,实现自己的需求
好的到这里本篇文章就先到此了,创作不易,如果那里有不合适的地方还请大家多多指教,写这篇博的目的主要就是为了方便自己以后的一个回忆和朋友学习时的一个参考,希望为大家可以带来帮助 ~ ~&
虚心的去学习,自信的去工作~