spring boot注册登录页面设计代码
时间: 2024-04-11 09:23:32 浏览: 24
当设计Spring Boot注册登录页面时,可以使用Thymeleaf模板引擎和Spring Security来实现用户认证和授权功能。下面是一个简单的示例代码:
1. 创建一个Spring Boot项目,并添加以下依赖:
```xml
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
```
2. 创建一个Controller类,处理注册和登录请求:
```java
@Controller
public class UserController {
@GetMapping("/register")
public String showRegistrationForm() {
return "register";
}
@PostMapping("/register")
public String processRegistration(User user) {
// 处理用户注册逻辑
return "redirect:/login";
}
@GetMapping("/login")
public String showLoginForm() {
return "login";
}
}
```
3. 创建Thymeleaf模板文件,用于展示注册和登录页面:
register.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Registration</title>
</head>
<body>
<h2>Registration</h2>
<form th:action="@{/register}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<button type="submit">Register</button>
</form>
</body>
</html>
```
login.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form th:action="@{/login}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
```
4. 配置Spring Security,设置用户认证和授权规则:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/register", "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
}
```
以上代码示例了一个简单的Spring Boot注册登录页面设计,使用Thymeleaf模板引擎和Spring Security实现用户认证和授权功能。