代码生成(springboot简单登录功能)
时间: 2023-07-26 22:33:58 浏览: 40
以下是一个简单的 Spring Boot 登录功能代码示例:
首先,在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后,在 application.yml 文件中添加以下配置:
```yaml
spring:
security:
user:
name: admin
password: password
```
上面的配置表示默认用户名为 admin,密码为 password。
接下来,创建一个 WebSecurityConfig 类,用于配置 Spring Security:
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("password").roles("USER");
}
}
```
在上面的代码中,我们定义了登录页面、权限控制等配置。
最后,我们需要在 Spring Boot 应用程序的入口类中添加以下代码:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Controller
public static class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
}
}
```
在上面的代码中,我们定义了首页和登录页面的访问路径。
好了,以上就是一个简单的 Spring Boot 登录功能代码示例,供你参考。