SpringBoot学习5.0-SpringMVC集成thymeleaf简单例子

目录

1.maven坐标

2.项目结构

3.配置视图解析器

4.Controller跳转访问模板

5.模板文件

6.测试

6.1.访问static下的html文件

6.2.跳转访问模板

7.总结

8.引入js


1.maven坐标

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

必须增加web。

增加thymeleaf的依赖,视图解析器可以访问templates下的静态文件。

2.项目结构

资源目录templates是thymeleaf的默认路径,增加thymeleat的依赖后,可以通过视图解析器访问模板。

static目录下的文件可以直接访问。

3.配置视图解析器

#定义视图解析器的规则
#文件前缀,templates是thymeleafd的默认路径
spring.mvc.view.prefix=classpath:/templates/
#文件后缀
spring.mvc.view.suffix=.html

4.Controller跳转访问模板

package com.zyf.springMVC.mvcview;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
@RequestMapping("/mvcview")
public class MvcViewController {
 
	@RequestMapping("/v1")
	public ModelAndView mvc1() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("mvcview/v1");
		modelAndView.addObject("username", "张三");
		return modelAndView;
	}
	@RequestMapping("/v2")
	public String mvc2() {
		return "mvcview/v2";
	}
}

视图解析器的规则配置后,【前缀 + 类名的RequestMapping + viewname + 后缀】就可以定位模板文件。

5.模板文件

v1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>hello spring mvc v1</p>
	<p th:text="${username}"></p>
</body>
</html>

v2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>hello spring mvc v2</p>
</body>
</html>

6.测试

6.1.访问static下的html文件

浏览器输入http://localhost:8080/ 或者http://localhost:8080/index.html,都可以访问index.html模板。

但是要访问index2.html则只能输入:http://localhost:8080/index2.html

6.2.跳转访问模板

如果没有添加thymeleat的依赖,无法访问templates下的模板,会有404错误。

 

7.总结

  • 资源目录templates是thymeleaf的默认路径,要想访问templates下的静态文件,必须增加web和thymeleaf的依赖,可以通过视图解析器访问模板。
  • static目录下的文件可以直接访问,首页放在这个位置。
  • 视图解析器的规则配置好,视图解析器通过【前缀 + 类名的RequestMapping + viewname + 后缀】定位模板文件。

 

8.引入js


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>user</title>
<script th:src="@{/js/jquery/jquery-3.4.1.js}"></script>
<script th:src="@{/js/test.js}"></script>
</head>
<body>
	<button id="insert">新建</button>
</body>
</html>

以上引入js是按照thymeleaf语法,默认是static下。

在线jquery可以如下写:

<!-- 加载Query文件-->
<script src="https://code.jquery.com/jquery-3.2.0.js">

 

github:https://github.com/zhangyangfei/SpringBootLearn.git中的springMVC工程。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值