SpringBoot学习5.0-SpringMVC简单例子

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的依赖。

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";
	}
}

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错误。

 

 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章