I'm currently doing a backend service in Java and Springboot allowing to create users in a MongoDB database. I use Swagger to make it easier to test my queries. Currently, I have a UserController that allows to create a user in my database.
UserController:
package demomongo;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
@RestController@RequestMapping("/api/users")
public class UserController {
private final MongoTemplate mongoTemplate;
public UserController(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@RequestMapping(value = "/createUser", headers = {
"content-type=application/json" }, consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public ResponseEntity<UserToto> createUser(@RequestBody UserToto user) {
// Sauvegarde l'utilisateur dans la base de données
mongoTemplate.save(user, "users");
// Retourne l'utilisateur sauvegardé avec le code de statut 201 (Created)
ResponseEntity<UserToto> responseEntity = ResponseEntity.status(HttpStatus.CREATED).body(user);
return responseEntity;
}
}
All the information I provide is lost in the @RequestBody.
This is my User class:
package demomongo;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "users")
public class UserToto {
@Id
public String id;
@Field("username")
public String username;
@Field("password")
public String password;
@Field("email")
public String email;
@Field("role")
public ERole role;
public UserToto() {
// TODO Auto-generated constructor stub
}
public UserToto(String username, String password, String email, ERole role) {
this.username = username;
this.password = password;
this.email = email;
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public ERole getRole() {
return role;
}
public void setRole(ERole role) {
this.role = role;
}
}
And I see this when I run a query in the console (I am in debug) :
Cookie: _ga=GA1.1.1509338151.1640108306; _ga_635PSCWLD2=GS1.1.1640358628.4.1.1640361429.0
{
"id": "string",
"username": "qqzqdqz",
"password": "qqzsqz",
"email": "string",
"role": "ADMIN"
}]
2023-02-25 17:48:34.000 DEBUG 3176 --- [nio-8080-exec-3] o.a.t.util.http.Rfc6265CookieProcessor : Cookies: Parsing b[]: _ga=GA1.1.1509338151.1640108306; _ga_635PSCWLD2=GS1.1.1640358628.4.1.1640361429.0
2023-02-25 17:48:34.000 DEBUG 3176 --- [nio-8080-exec-3] o.a.c.authenticator.AuthenticatorBase : Security checking request POST /api/users/createUser
2023-02-25 17:48:34.000 DEBUG 3176 --- [nio-8080-exec-3] org.apache.catalina.realm.RealmBase : No applicable constraints defined
2023-02-25 17:48:34.000 DEBUG 3176 --- [nio-8080-exec-3] o.a.c.authenticator.AuthenticatorBase : Not subject to any constraint
2023-02-25 17:48:34.001 DEBUG 3176 --- [nio-8080-exec-3] org.apache.tomcat.util.http.Parameters : Set encoding to UTF-8
2023-02-25 17:48:34.001 DEBUG 3176 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : POST "/api/users/createUser", parameters={}
2023-02-25 17:48:34.001 DEBUG 3176 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to demomongo.UserController#createUser(UserToto)
2023-02-25 17:48:34.002 DEBUG 3176 --- [nio-8080-exec-3] o.s.data.mongodb.core.MongoTemplate : Saving Document containing fields: [_class]
2023-02-25 17:48:34.002 DEBUG 3176 --- [nio-8080-exec-3] org.mongodb.driver.operation : retryWrites set to true but the server is a standalone server.
2023-02-25 17:48:34.003 DEBUG 3176 --- [nio-8080-exec-3] org.mongodb.driver.protocol.command : Sending command '{"insert": "users", "ordered": true, "$db": "local", "lsid": {"id": {"$binary": {"base64": "ZqkevgwVRNW11lq6aFInlg==", "subType": "04"}}}, "documents": [{"_id": {"$oid": "63fa3be2d71e155ac3ed737a"}, "_class": "demomongo.UserToto"}]}' with request id 130 to database local on connection [connectionId{localValue:3, serverValue:361}] to server localhost:27017
2023-02-25 17:48:34.003 DEBUG 3176 --- [nio-8080-exec-3] org.mongodb.driver.protocol.command : Execution of command with request id 130 completed successfully in 1.03 ms on connection [connectionId{localValue:3, serverValue:361}] to server localhost:27017
2023-02-25 17:48:34.004 DEBUG 3176 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2023-02-25 17:48:34.004 DEBUG 3176 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [demomongo.UserToto@446d6913]
2023-02-25 17:48:34.005 DEBUG 3176 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 201 CREATED
2023-02-25 17:48:34.006 DEBUG 3176 --- [nio-8080-exec-3] o.a.coyote.http11.Http11InputBuffer : Before fill():
Here is my POM and my Run class :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
</parent>
<groupId>demomongo</groupId>
<artifactId>demomongo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
<springfox.version>3.0.0</springfox.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package demomongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@SpringBootApplication
public class Run implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Run.class, args);
}
public void run(String... args) throws Exception {
}
}
I hope I was clear enough... thanks to all
I think that the problem here is your RequestBody import. It is using the one from swagger, not from spring! It should be
org.springframework.web.bind.annotation.RequestBody;
And if I may, I'd suggest you to change from springfox to springdoc as there is some good things about this change.