首页 技术 正文
技术 2022年11月12日
0 收藏 363 点赞 4,719 浏览 1625 个字

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. 引入springmvc

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对应的值。这个项目结构图如下:

2. 引入springmvc

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295