springboot实现退出登录的功能完整代码
时间: 2023-09-08 11:08:31 浏览: 120
springboot代码
以下是Spring Boot实现退出登录功能的完整代码:
1. 创建一个名为SecurityConfig的类,用于配置Spring Security。
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/logout").permitAll()
.antMatchers("/home").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/home")
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
```
2. 创建一个名为UserDetailsServiceImpl的类,实现UserDetailsService接口,用于从数据库中获取用户信息。
```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("User not found");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
private List<GrantedAuthority> getAuthorities(User user) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
}
```
3. 创建一个名为UserRepository的接口,继承JpaRepository接口,用于从数据库中获取用户信息。
```java
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
4. 创建一个名为UserController的类,用于处理登录和退出登录的请求。
```java
@Controller
public class UserController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
new SecurityContextLogoutHandler().logout(request, response, authentication);
}
return "redirect:/login?logout";
}
@GetMapping("/home")
public String home() {
return "home";
}
}
```
5. 创建一个名为User的类,用于表示用户信息。
```java
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles;
// getters and setters
}
```
6. 创建一个名为Role的类,用于表示角色信息。
```java
@Entity
@Table(name = "role")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@ManyToMany(mappedBy = "roles")
private List<User> users;
// getters and setters
}
```
7. 创建一个名为SpringBootSecurityApplication的类,用于启动Spring Boot应用程序。
```java
@SpringBootApplication
public class SpringBootSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}
```
以上就是Spring Boot实现退出登录功能的完整代码。
阅读全文