我想spring boot实现一个登录业务,在html页面可以点击登录后,发起请求给后端,登录成功后,转到新的html界面,显示登录成功
时间: 2023-12-07 21:05:38 浏览: 34
好的,首先你需要在后端实现一个登录接口,接受前端传来的登录信息进行校验,如果校验通过则返回登录成功的信息。
你可以使用Spring Security框架来实现登录校验,具体步骤如下:
1.在pom.xml文件中添加Spring Security依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2.在Spring Boot主类上添加@EnableWebSecurity注解,启用Spring Security:
```
@EnableWebSecurity
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
3.创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法,配置登录认证信息:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll() // 登录页面不需要认证
.anyRequest().authenticated() // 其他页面需要认证
.and()
.formLogin()
.loginPage("/login") // 指定登录页面
.defaultSuccessUrl("/index") // 登录成功后跳转的页面
.permitAll()
.and()
.logout()
.permitAll();
}
}
```
4.在Controller中添加登录接口,接受前端传来的登录信息进行校验,如果校验通过则跳转到登录成功页面:
```
@Controller
public class LoginController {
@PostMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session) {
if (username.equals("admin") && password.equals("123456")) {
session.setAttribute("username", username);
return "redirect:/index";
} else {
return "redirect:/login";
}
}
}
```
5.在前端页面中添加登录表单,提交表单时发起登录请求:
```
<form action="/login" method="post">
<input type="text" name="username"/>
<input type="password" name="password"/>
<button type="submit">登录</button>
</form>
```
6.在登录成功页面中显示登录成功信息:
```
<h1>登录成功!</h1>
```
以上就是一个简单的Spring Boot登录业务的实现步骤。