2. 引入springmvc

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类代码如下:

 1 package com.lvniao.blog;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.ui.Model;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 
 9 @Controller
10 @SpringBootApplication
11 public class App 
12 {
13     @RequestMapping("/")
14     public String index(Model model) {
15         model.addAttribute("hello", "Hello, World!");
16         return "index";
17     }
18     
19     public static void main( String[] args )
20     {
21            SpringApplication.run(App.class, args);
22     }
23 }
App.java

先是把@RestController修改为@Controller,然后在index中加Model参数,这样自动注入视图模型,然后在方法中给视图模型添加相关值,并返回"index",这样视图解析器就会根据application.properties中配置的前后缀来在src/main/resources(也就是classpath目录)中寻找对应的视图文件,这样就要在templates中添加index.html视图,代码如下:

1 <html>
2 <head>
3 <title>vue demo</title>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5 </head>
6 <body>
7     <h1 th:text="${hello}"></h1>
8 </body>
9 </html>
index.html

在代码中通过th:text="${hello}"来绑定视图模型中的hello对应的值。这个项目结构图如下:

如上,就完成了springmvc的引入。

猜你喜欢

转载自www.cnblogs.com/lvniao/p/9038751.html
2.