springboot+thymeleaf登入功能实现
时间: 2023-08-27 16:06:56 浏览: 155
SpringBoot+MyBatisPlus+Thymeleaf 增删改查CRUD
5星 · 资源好评率100%
好的,下面是一个简单的Spring Boot + Thymeleaf登录功能实现的示例。
1. 首先,我们需要在pom.xml文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. 在application.properties文件中添加如下配置:
```properties
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Thymeleaf配置
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.template-resolver-order=1
spring.thymeleaf.view-names=*.html
```
3. 创建一个用户实体类User.java:
```java
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
4. 创建一个登录控制器LoginController.java:
```java
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String login(@ModelAttribute User user, Model model) {
if ("admin".equals(user.getUsername()) && "123456".equals(user.getPassword())) {
return "success";
} else {
model.addAttribute("error", "用户名或密码错误");
return "login";
}
}
}
```
5. 在src/main/resources/templates目录下创建一个名为login.html的登录页面:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h1>登录页面</h1>
<form th:action="@{/login}" method="post">
<p>
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
</p>
<p>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
</p>
<p>
<button type="submit">登录</button>
</p>
<p th:text="${error}" style="color:red"></p>
</form>
</body>
</html>
```
6. 在src/main/resources/templates目录下创建一个名为success.html的登录成功页面:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录成功</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
```
7. 启动应用程序,并访问http://localhost:8080/login进行登录。
以上就是一个简单的Spring Boot + Thymeleaf登录功能实现的示例。
阅读全文