要实现表单提交导致POST请求,触发登录页面中的UsernamePasswordAuthenticationFilter,可以使用Spring Security来处理用户认证。以下是一个示例代码:
首先,确保已经添加了Spring Security的依赖。
Login
Login
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String authenticate(HttpServletRequest request, HttpServletResponse response) {
String username = request.getParameter("username");
String password = request.getParameter("password");
// 使用Spring Security的AuthenticationManager来进行用户认证
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
try {
Authentication authentication = authenticationManager.authenticate(token);
// 将认证信息保存到SecurityContextHolder中
SecurityContextHolder.getContext().setAuthentication(authentication);
// 重定向到主页或其他受保护的页面
return "redirect:/home";
} catch (AuthenticationException e) {
// 处理认证失败的情况
return "redirect:/login?error";
}
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.and()
.csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在这个例子中,登录表单的提交将会导致POST请求,触发UsernamePasswordAuthenticationFilter来进行用户认证。登录成功后,用户将被重定向到主页(/home),登录失败则重定向回登录页面并显示错误信息。
请注意,这只是一个基本示例,实际应用中还需要根据具体需求进行适当的配置和处理。