springboot提供了spring-web-starter-web为web开发提供了支持,并且内嵌了tomcat及spring mvc的依赖,而且通过spring-boot-autoconfigure.jar中的相关类提供了自动配置,开发者只需遵守相关约定即可直接使用。因为spring boot默认是使用Thymeleaf作为模板引擎的,所以要引入Thymeleaf的依赖,如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后需要将App类中的@RestController修改为@Controller,这样action的返回值才能经过视图解析器处理,相关步骤如下:
1. 添加src/main/resources命名的Source Folder目录
2. 然后在该目录中添加static目录(用于保存静态资源文件)、templates目录(用于保存视图文件)以及application.properties文件(作为系统的配置文件)。并在application.properties文件中添加如下内容:
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html
这样声明了action放回字符串对应视图的前缀和后缀;
3. 修改App类代码如下:
package com.lvniao.blog; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@SpringBootApplication
public class App
{
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("hello", "Hello, World!");
return "index";
} public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
App.java
先是把@RestController修改为@Controller,然后在index中加Model参数,这样自动注入视图模型,然后在方法中给视图模型添加相关值,并返回”index”,这样视图解析器就会根据application.properties中配置的前后缀来在src/main/resources(也就是classpath目录)中寻找对应的视图文件,这样就要在templates中添加index.html视图,代码如下:
<html>
<head>
<title>vue demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1 th:text="${hello}"></h1>
</body>
</html>
index.html
在代码中通过th:text=”${hello}”来绑定视图模型中的hello对应的值。这个项目结构图如下:
如上,就完成了springmvc的引入。