写在前面:从2018年底开始学习SpringBoot,也用SpringBoot写过一些项目。现在对学习Springboot的一些知识总结记录一下。如果你也在学习SpringBoot,可以关注我,一起学习,一起进步。相关文章:Thymeleaf模板的使用
相关文章:
【Springboot系列】Springboot入门到项目实战
目录
搭建项目
1、项目结构
2、搭建SpringBoot项目
选择相关的依赖,相关依赖有:spring-web和Thymeleaf
3、相关依赖
完整的pom.xml依赖文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mcy</groupId>
<artifactId>spring-thy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-thy</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--starter-web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
如果新建项目时没有勾选Thymeleaf依赖,则需要手动添加Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
编写代码
1、登录页面
先在templates文件夹下新建一个index.html登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
#main{
width: 400px;
margin: 100px auto;
padding: 30px;
border-radius: 20px;
border: 10px solid lightsteelblue;
text-align: center;
}
p{
font-size: 25px;
padding: 10px;
}
input{
width: 250px;
border-radius: 3px;
height: 20px;
font-size: 25px;
padding: 3px;
}
button{
width: 100px;
padding: 10px;
border-radius: 5px;
border: none;
background: blue;
color: white;
}
</style>
</head>
<body>
<div id="main">
<form action="login" method="post">
<!--name值对应后台Controller中接收的变量-->
<p>账号:<input type="text" name="username" placeholder="账号"></p>
<p>密码:<input type="password" name="password" placeholder="密码"></p>
<p><button type="submit">登录</button></p>
</form>
</div>
</body>
</html>
【注意】input中name属性值对应后台Controller中接收的变量。
2、测试控制器
在【com.mcy.demo】包下新建一个【controller】包,【com.mcy.demo.controller】包下新建一个【Indexcontroller.java】类:
@Controller
public class IndexController {
//映射“/”请求
@RequestMapping("/")
public String index(){
System.out.println("index方法被调用。。。。");
//根据Thymeleaf默认模板,将返回resources/templates/index.html
return "index";
}
//登录请求
//username, password对应前台input中name属性值
@PostMapping("login")
public String login(String username, String password){
System.out.println("login方法被调用。。。。");
System.out.println("login登录名:"+username+", 密码:"+password);
//重定向到main请求
return "redirect:/main";
}
//跳转登录成功后页面请求
@RequestMapping(value="/main")
public String main(){
System.out.println("main方法被调用。。。。");
//返回main页面
return "main";
}
}
【注意】login方法中参数username, password对应前台input中name属性值
@Controller注解用于指示该类是一个控制器。@RequestMapping注解用于映射请求的URL,@PostMapping注解对应post映射请求。
返回字符串"index",由于Thymeleaf默认的前缀是“classpath:/templates/”,后缀是“html”,所以该请求返回“classpath:/templates/index.html”。
登录成功返回main.html页面,代码如下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
登录成功,欢迎页面。
</body>
</html>
测试应用
1、参数传递
运行项目,直接浏览器localhost:8080访问,请求会提交到IndexController类的index方法进行处理,该方法返回字符串“index”,即跳转到templates/index.html页面。
输入任意登录名,密码单击登录按钮。请求将会提交到IndexController类的login方法,该方法接收请求参数username和password,并重定向到main请求。main请求的处理方法是IndexController类中的main方法,该方法返回字符串"main",即跳转到templates/main.html页面,如图所示。
查看idea控制台输出结果
控制台输出的为接收到前台传递的参数以及方法被调用信息。
在main.html页面上添加三个测试超连接,分别用来测试Thymeleaf的表达式,条件判断和循环。
<body>
<p>登录成功,欢迎页面。</p>
<p>a标签中的href属性可以用href也可以用th:href</p>
<p><a th:href="@{regexptest?username=jack&password=123456}">测试表达式访问数据</a></p>
<p><a th:href="@{iftest}">测试条件判断</a></p>
<p><a href="eachtest">测试循环</a></p>
</body>
2、表达式访问数据
第一个测试表达式访问数据,对应IndexController中的regexptest方法代码如下
//将表达式保存到作用域,用于测试Thymeleaf表达式访问数据
@RequestMapping(value = "/regexptest")
public String regexptest(HttpServletRequest request, HttpSession session){
//将数据保存到request作用域中
request.setAttribute("book", "springboot整合Thymeleaf");
//将数据保存到session作用域中
session.setAttribute("belong", "spring");
//将数据保存到servletContext(application)作用域当中
request.getServletContext().setAttribute("name", "Thymeleay模板");
return "success";
}
regexptest方法用来响应第一个请求<a th:href="@{regexptest?loginName=jack↦ password=123456}">测试表达式访问数据</a>,regexptest方法中设置了一个book变量到request作用域;设置了一个belong变量到session作用域;设置了一个name变量到servletContext全局作用域,然后返回success.html页面。
success.html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>Thymeleaf表达式访问数据</h3>
<p style="color: red;">${param.x}将返回一个名为x的请求参数</p>
<p>
访问页面传递的参数:<span th:text="${param.username[0]}">登录名</span>,
<span th:text="${param.password[0]}">密码</span>
</p>
<p style="color: red;">${x}将返回存储在Thymeleaf上下文中的变量X或作为请求Request作用范围域中的属性。</p>
<p>访问request作用范围域中的变量:<span th:text="${book}">图书信息</span></p>
<p style="color: red;">${sessin.x}将返回一个名为x的会话HTTPSession作用范围域中的属性。</p>
<p>访问session作用范围域中的变量:<span th:text="${session.belong}">属于</span></p>
<p style="color: red;">${application.x}将返回一个名为x的全局ServletContext上下文作用范围域中的属性。</p>
<p>访问application作用范围域中的变量:<span th:text="${application.name}">动态页面模板</span></p>
</body>
</html>
success.html中通过使用Thymeleaf表达式,接收了请求传递的参数username和password,并分别访问了控制器中保存在request、session和application中的三个变量。
有一些专门的表达式,用来从模板中的WebContext获取请求参数、请求、会话和应用程序中的属性,这些操作和JSP的EL表达式非常相似。
- ${X}将返回存储在Thymeleaf上下文中的变量X或作为请求Request作用域中的属性。
- ${param.x}将返回一个名为x的请求参数(可能是多值的)。
- ${session.x}将返回一个名为x的会话HTTPSession作用域中的属性。
- ${application.x}将返回一个名为x的全局ServletContext上下文作用域中的属性。
项目运行后,直接浏览器localhost:8080/main访问。之后点击测试表达式访问数据可以看到,请求参数和保存在request,session和application作用域中的数据都访问到了,如图
可以看到,请求参数和保存在request,session和application作用域中的数据都访问到了。
3、条件判断
第二个测试Thymeleaf添加判断,对应IndexController中的iftest方法
//将数据保存到作用域,用于测试Thymeleaf的条件判断
@RequestMapping(value = "/iftest")
public String iftest(WebRequest webRequest, ModelMap map){
//将数据保存到request作用域,SpringMVC推荐使用WebRequest或者ModelMap
webRequest.setAttribute("username", "fkit", webRequest.SCOPE_REQUEST);
webRequest.setAttribute("age", 21, webRequest.SCOPE_REQUEST);
//ModelMap传递
map.put("role", "admin");
return "success2";
}
iftest方法用来响应第二个请求<a th:href="@{iftest}">测试条件判断</a>,iftest方法中分别设置了username,age和role三个变量到request作用域,然后返回success2.html。
success2.html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>Thymeleaf条件判断</h3>
<p style="color: red;">th:if中条件成立时才显示结果</p>
<p><span th:if="${username != null}">username不为空</span></p>
<p><span th:if="${age != null}">age不为空</span></p>
<p style="color: red;">th:unless与th:if恰好相反,只有表达式中的条件不成立,才会显示结果</p>
<p th:unless="${address != null}">address为空</p>
<p style="color: red;">支持多路选择Switch结构,默认属性default可以用*表示</p>
<div th:switch="${role}">
<p th:case="'admin'">管理员</p>
<p th:case="'guest'">来宾</p>
<p th:case="'*'">其他</p>
</div>
</body>
</html>
项目运行后,直接浏览器localhost:8080/main访问。之后点击测试条件判断,请求进入了控制器iftest方法,返回success2.html页面,如图:
4、循环获取数据
第三个测试Thymeleaf循环取数据。
先创建一个Book类,设计了id,title,author和price属性,用来保存图片信息,便于之后存取数据。
public class Book {
private Integer id;
private String title; //书名
private String author; //作者
private String price; //价格
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Book(Integer id, String title, String author, String price) {
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
public Book() {
}
}
测试Thymeleaf循环取数据,对应IndexController中的eachtest方法
//将数据保存到作用域,用于测试Thymeleaf的循环获取数据
@RequestMapping(value = "/eachtest")
public String eachtest(ModelMap map){
//模拟数据库数据保存到list集合
List<Book> book = new ArrayList<>();
book.add(new Book(1, "HTML5+CSS3", "张三", "20"));
book.add(new Book(2, "JavaScript", "李四", "30"));
book.add(new Book(3, "java编程思想", "王五", "40"));
//将数据保存到Request作用域中
map.put("book", book);
return "success3";
}
eachtest方法用来响应第三个请求<a th:href="@{eachtest}">测试循环</a>,eachtest方法中创建了3个book对象,分别保存3本图书信息,在创建一个List集合,将所用图书信息保存到List集合,最后将List集合保存到request作用域,然后返回success3.html。
success3.html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>Thymeleaf循环</h3>
<table border="1" cellspacing ="0" width="600px">
<tr>
<th>书名</th>
<th>作者</th>
<th>价格</th>
</tr>
<tr th:each="b:${book}">
<th th:text="${b.title}"></th>
<th th:text="${b.author}"></th>
<th th:text="${b.price}"></th>
</tr>
</table>
</body>
</html>
项目运行后,直接浏览器localhost:8080/main访问。之后点击测试循环,请求进入了控制器eachtest方法,返回success3.html页面,如图:
可以看到,使用th:each可以将集合数据很方便地提取出来并显示在HTML页面上。
案例代码下载地址:GitHub - machaoyin/spring-thy: Springboot整合Thymeleaf模板
SpringBoot中Jsp的使用
1、Springboot中Jsp的使用
如果不想用Thymeleaf模板,springboot也可以使用jsp
首先需要引入依赖:
<dependencies>
<!--添加spring-boot-starter-web模块依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加servlet依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- 添加jstl标签库依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--添加tomcat依赖模块.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
在application.properties配置文件中,添加页面配置信息,使之支持jsp
#页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
#响应页面默认后缀
spring.mvc.view.suffix=.jsp
配置完成后在webapp/WEB-INF/jsp文件夹下放jsp文件(必须有webapp/WEB-INF这个包,否则访问不到)
之后页面上和JSTL标准标签库用法一样。
有什么不足之处,欢迎大家指出,期待与你的交流。