SpringMVC 前后端传参

ModelAndView + thymeleaf

废话不多说,直接上demo。

properties:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ----------------------Springmvc配置-----------------------------
# 指定前端页面的前缀
spring.mvc.view.prefix=/
# 指定前端页面的后缀
spring.mvc.view.suffix=.html
# ------------------------thymeleaf配置-----------------------------------
spring.thymeleaf.servlet.content-type=text/html
# 指定文件路径
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template=false
spring.thymeleaf.check-template-location=false
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false

maven:

1
2
3
4
5
6
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 省略其他springboot包 -->

controller:

1
2
3
4
5
6
7
8
9
10
11
// 页面跳转controller
@Controller
public class PageController {
@RequestMapping("/")
public ModelAndView index() {
ModelAndView mav = new ModelAndView();
mav.addObject("testParam", "欧吼");
mav.setViewName("index");
return mav;
}
}

html:

1
2
3
4
5
6
7
8

<html lang="zh-CN"
xmlns:th="http://www.thymeleaf.org">
<script th:inline="javascript">
var testParam = [[${testParam}]];
console.log(testParam)
</script>
</html>

效果: