I am developing spring boot api project. @PostMapping
annotation does not running. Why? I added breakpoint but not stopping?? Please help.
pom.xml
...
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
...
ApplicationUser.java
public class ApplicationUser {
private long id;
private String name;
// constructors, getters-setters
}
ApplicationUserController.java
@RestController
@RequestMapping("/api/v1/users")
public class ApplicationUserController {
public static final List<ApplicationUser> USERS = Arrays.asList(
new ApplicationUser(1, "Jeff"),
new ApplicationUser(2, "Mark"),
new ApplicationUser(3, "Bill")
);
@GetMapping(value="/{userId}", produces="application/json")
public ResponseEntity<ApplicationUser> getUser(@PathVariable("userId") Long userId) {
return ResponseEntity.ok(
USERS.stream()
.filter(user -> userId.equals(user.getId()))
.findFirst()
.orElseThrow(() -> new IllegalStateException(
"User " + userId + "does not exists"
))
);
}
@PostMapping(value="/add", consumes="application/json")
public void addUser(@RequestBody ApplicationUser user) {
for (long i = 0L; i < USERS.size(); i++)
if (user.getId() == USERS.get((int)i).getId())
throw new IllegalStateException("User " + user.getId() + " already exists");
USERS.add(user);
}
}
ApplicationSecurityConfig.java
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
I tried following command
~$ curl http://localhost:8080/api/v1/users/add -X POST -H 'Content-type: application/json' -d '{"id": 4, "name": "Steve"}' -u user:-spring-security-password-
(no response)
After was running above command, i tried followings
~$ curl http://localhost:8080/api/v1/users/1 -u user:-spring-security-password-
{"id":1,"name":"Jeff"}
~$ curl http://localhost:8080/api/v1/users/4 -u user:-spring-security-password-
{"timestamp":"2021-01-20T19:53:19.205+00:00","status":500,"error":"Internal Server Error","message":"","path":"/api/v1/users/4"}
-- Edit --
I tried POST
request with Postman, gets 401 Unauthorized
. When try GET
request, runs properly.