springboot引入模板
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
springboot引⼊模板
今天主要说下,配置在resources⽂件中的内容怎样被spring boot所引⽤。
根据springboot 推荐的格式,我们知道放在resources 都是⼀些资源,包括整个项⽬的配置啊,⾃定义配置啊,静态资源⽂件(js,css 等),以properties结尾。
字⾯意思就是属性暂且就这么翻译吧。
application.properties是项⽬资源的配置,⽐如jar包的配置啊,⽐如默认端⼝是8080 但是我们想改成其他端⼝,怎么办了。
只需要在这个系统配置⽂件⾥加上
server.port=端⼝号
当然,还有很多其他的⽅法,但是有这个简单吗。
下⾯来做个实例来演⽰如何把⼀个定义在静态资源⽂件的值映射到⼀个对象上;
1. 新建⼀个com.xiaofeng.feng.pojo包,添加实体类Resource.java:
package com.xiaofeng.feng.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ConfigurationProperties(prefix="com.xiaofeng.feng")
@PropertySource(value="classpath:response.properties")
public class Resource {
private String name;
private String website;
private String language;
public String getName() {
return ;
}
public String getWebsite(){
return this.website;
}
public String getLanguage(){
return nguage;
}
public void setName(String name) {
=name;
}
public void setWebsite(String website){
this.website = website;
}
public void setLanguage(String language){
nguage = language;
}
}
⽐较简单,定义了三个属性:name,website,language;
2.然后在resources下新建⼀个资源⽂件:resource.properties 定义如下:
3.在HelloWorldController⾥⾯新添加⼀个类成员变量
@Autowired
private Resource resource;
在写⼀个⽅法看下返回结果:
@RequestMapping("/getResource")
public Object getResource(){
Resource bean=new Resource();
BeanUtils.copyProperties(resource, bean);
return bean;
}
得到结果:
说明资源⽂件的内容已经成功映射到我们定义的类中了。
这个是为什么了,主要是
@Configuration
@ConfigurationProperties(prefix="com.xiaofeng.feng1")
@PropertySource(value="classpath:response.properties")
定义映射关系
Resource bean=new Resource();
BeanUtils.copyProperties(resource, bean);
绑定具体的值。
在这⾥顺带说下freemarker和thymeleaf 2种模板展⽰模板在spring boot中的整合。
thymeleaf
需要在pom.xml引⼊thymeleaf 包的引⽤
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
thymeleaf
在application.properties种配置如下
spring.thymeleaf.prefix=classpath:/templates/ /*模板的位置这⾥是在resources/templates下*/ spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.content-type=text/html
spring.thymeleaf.suffix=.html
新建⼀个ThymeleafController 实现如下:
@RequestMapping("/index")
public String index(ModelMap map){
map.addAttribute("name", "thymeleaf xiaofeng");
return "thymeleaf/index";
}
在templates/thymeleaf下新建⼀个index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>Insert title here</title>
</head>
<body>
Thymeleaf 模板引起
<h1 th:text="${name}">hello world~~</h1>
</body>
</html>
注意标签对要写好要不然会出错。
运⾏结果如下:
个⼈是⽐较推荐使⽤thymeleaf这个模板的,freemarker和它使⽤差不多,但是耦合⽐thymeleaf要⾼。