生成一个由Spring Security开发的登录页面,从数据库查询账号密码与用户登入的账号密码校验
时间: 2023-05-22 20:01:34 浏览: 66
您可以使用Spring Security提供的表单登录功能来生成登录页面。首先,您需要在Spring Security配置文件中配置表单登录,例如:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig 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=true")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
```
在上面的配置中,我们配置了一个登录页面为"/login",并且在登录成功后跳转到"/home"页面。我们还配置了一个失败页面为"/login?error=true",以及一个注销页面为"/login?logout=true"。
接下来,您需要创建一个登录页面,例如:
```
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br />
<label for="password">Password:</label>
<input type="password" id="password" name="password" /><br />
<input type="submit" value="Login" />
</form>
</body>
</html>
```
在上面的登录页面中,我们使用了一个表单来提交用户名和密码,表单的action为"/login",method为"post"。
最后,您需要实现一个UserDetailsService接口来从数据库中查询用户信息,并且在Spring Security配置文件中配置该接口,例如:
```
@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(), new ArrayList<>());
}
}
```
在上面的实现中,我们从数据库中查询用户信息,并且返回一个UserDetails对象,该对象包含了用户名、密码以及用户的角色信息。
最后,您需要在Spring Security配置文件中配置该UserDetailsService,例如:
```
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
```
这样,您就可以使用Spring Security提供的表单登录功能来生成登录页面,并且从数据库中查询账号密码与用户登入的账号密码校验了。