spring boot + Thymeleaf开发web项目 视图解析


声明:本文转载自https://my.oschina.net/bianxin/blog/1816920,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

很多人,都知道spring boot怎么进行接口开发,今天我就来讲讲怎么实现页面跳转,完成一个web项目。我就借助Thymeleaf模板引擎来举例:

导入相关jar包(pom)

<parent> 	<groupId>org.springframework.boot</groupId> 	<artifactId>spring-boot-starter-parent</artifactId> 	<version>2.0.1.RELEASE</version> 	<relativePath /> </parent> <properties> 	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 	<java.version>1.8</java.version> </properties> <dependencies> 	<dependency> 		<groupId>org.springframework.boot</groupId> 		<artifactId>spring-boot-starter-web</artifactId> 	</dependency> 	<dependency> 		<groupId>org.springframework.boot</groupId> 		<artifactId>spring-boot-starter-test</artifactId> 		<scope>test</scope> 	</dependency> 	<dependency> 		<groupId>org.springframework.boot</groupId> 		<artifactId>spring-boot-configuration-processor</artifactId> 		<optional>true</optional> 	</dependency> 	<!-- thymeleaf模板引擎 --> 	<dependency> 		<groupId>org.springframework.boot</groupId> 		<artifactId>spring-boot-starter-thymeleaf</artifactId> 	</dependency> </dependencies> 

你用spring-boot-starter-parent是2.0以上时,对应的thymeleaf是3.0以上的版本,相对较新,不要改。如果你用的是spring-boot-starter-parent 1.5,对应的thymeleaf是2.0以上的版本,建议用thymeleaf3.0的。

包选择为:

<dependency>     <groupId>org.thymeleaf</groupId>     <artifactId>thymeleaf-spring4</artifactId>  <!-- 如果spring是5:thymeleaf-spring5  -->     <version>3.0.9.RELEASE</version> </dependency>

静态资源文件映射规则

根据:WebMvcAutoConfiguration→addResourceHandlers→ResourceProperties
可知道:spring boot 默认的静态资源路径如下:

1、classpath:/
2、classpath:/META-INF/resources/
3、classpath:/resources/
4、classpath:/static/
5、classpath:/public/

也就是说可以直接访问以上路径中的文件。
如:
     
访问地址:http://127.0.0.1:8080/css/login.css (不需要加resources、static、public...)

thymeleaf默认的视图解析

可以看出,初始化的默认页面路径在classpath:/templates/ 下,视图后缀为.html。也可以根据自己的喜号在application.yml文件中 指定spring.thymeleaf.** =** 来指定值

实现请求URL

我就不改动了,采用默认值

/**  * @描述 	用户相关页面请求  * @注意		此类只能用@Controller 不能使用@RestController  * @author  BianP  */ @Controller   @RequestMapping("/user") public class UserWebController { 	/** 	 * @explain 用户登录《GET》 	 * @return  String 	 * @author  BianP 	 */ 	@RequestMapping(value="/toLogin", method = RequestMethod.GET) 	public String toLogin(Model model){ 		model.addAttribute("welcome", "欢迎登录"); 		return "login"; 	} }

目录结构

请求结果:

本文发表于2018年05月22日 22:00
(c)注:本文转载自https://my.oschina.net/bianxin/blog/1816920,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 1576 讨论 1 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1