springboot实现登录功能代码
时间: 2024-04-21 18:17:25 浏览: 231
springboot实现登录
4星 · 用户满意度95%
以下是一个简单的Spring Boot登录功能代码示例,使用了Spring Security和Thymeleaf模板引擎。
1. 配置文件application.properties
```
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
server.port=8080
spring.security.user.name=admin
spring.security.user.password=123456
spring.security.user.roles=admin
```
2. 建立数据库表结构
```
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
```
3. 创建User实体类
```java
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String email;
// 省略getter和setter
}
```
4. 创建UserRepository
```java
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
5. 创建登录页面login.html
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<div th:if="${param.error}">
Invalid username or password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
```
6. 创建HomeController
```java
@Controller
public class HomeController {
@Autowired
private UserRepository userRepository;
@RequestMapping(value = {"/", "/home"})
public String home() {
return "home";
}
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/logout")
public String logout() {
return "logout";
}
@RequestMapping("/register")
public String register(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping("/register")
public String createUser(@ModelAttribute("user") User user) {
userRepository.save(user);
return "redirect:/login";
}
}
```
7. 创建SecurityConfig
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/success")
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
```
8. 创建UserDetailsServiceImpl
```java
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
getAuthority(user));
}
private Set<SimpleGrantedAuthority> getAuthority(User user) {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));
return authorities;
}
}
```
9. 运行程序并访问localhost:8080/login进行登录。
阅读全文