我的@RequestBody 返回我的带有空变量的对象

问题描述 投票:0回答:1

我目前正在使用 Java 和 Springboot 做后端服务,允许在 MongoDB 数据库中创建用户。我使用 Swagger 来更轻松地测试我的查询。目前,我有一个 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;
}
}

我提供的所有信息都丢失在@RequestBody中。

这是我的用户类:

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;
    }

}

我在控制台中运行查询时看到了这个(我正在调试):


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(): 

这是我的 POM 和我的运行类:

<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 {

    }

}

我希望我已经足够清楚了......感谢所有人

java spring-boot swagger http-post
1个回答
0
投票

我认为这里的问题是你的 RequestBody 导入。它使用的是来自 swagger 的那个,而不是来自 spring 的! 应该是

org.springframework.web.bind.annotation.RequestBody;

如果可以的话,我建议您从 springfox 更改为 springdoc,因为此更改有一些好处。

© www.soinside.com 2019 - 2024. All rights reserved.