请给出一个简单的spring security示例程序,在访问本地端口时需要输入用户名和密码才能看到hello world,请详细描述controller以及其他关键的类和文件
时间: 2024-03-11 10:48:13 浏览: 22
好的,下面是一个简单的Spring Security示例程序,其中在访问本地端口时需要输入用户名和密码才能看到“Hello, World!”:
1.首先,需要在pom.xml文件中添加Spring Security依赖,例如:
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.5.1</version>
</dependency>
```
2.然后,需要创建一个Spring Security配置类,例如:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").hasRole("USER")
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
```
3.在上述配置类中,我们指定了一个用户,并且定义了一个URL模式,该URL模式需要用户权限才能访问。最后,我们配置了一个简单的登录表单和注销功能。
4. 接下来,需要创建一个Spring MVC的Controller类,例如:
```java
@Controller
public class HelloController {
@GetMapping("/")
public String hello() {
return "hello";
}
}
```
5. 在上述Controller类中,我们定义了一个处理根路径请求的方法,该方法返回名为“hello”的视图。
6. 最后,需要创建一个名为“hello.jsp”的JSP视图,例如:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
```
7. 在上述JSP视图中,我们简单地显示了一条欢迎消息。
现在,你可以在浏览器中访问该应用程序,并尝试访问根路径。你会发现只有在输入正确的用户名和密码后才能看到“Hello, World!”消息。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)