【问题标题】:Bad request in RestController spring boot 2.7RestController spring boot 2.7 中的错误请求
【发布时间】:2023-01-13 01:07:29
【问题描述】:

我检查了几种不同的方法来检查错误在哪里,但我仍然不知道答案。

那是我的 RestController

@RestController
public class CustomerController {
    @PostMapping(value = "/customer")
    public ResponseEntity<CustomerResponse> addCustomer(@RequestBody @Valid Customer custRequest) throws Exception {
        ModelMapper modelMapper = new ModelMapper();
        CustomerDto customerDto = modelMapper.map(custRequest, CustomerDto.class);
        CustomerDto addCust = customer.addCustomer(customerDto);
        CustomerResponse custResponse = modelMapper.map(addCust, CustomerResponse.class);
        return new ResponseEntity<CustomerResponse>(custResponse, HttpStatus.CREATED);
    }
}

那是我的模特

@Entity
@Table(name = "customers")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String idCustomer;
    private String email;
    @OneToMany(mappedBy = "customer",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private List<Choice> choices;
    // Getter and setter and constructor
}

Maven 依赖项

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>

邮递员的回应

我该如何解决这个问题才能发布新客户。

【问题讨论】:

  • 不要在控制器级别使用实体类。这是非常糟糕的架构
  • 错误的请求意味着您的请求没有到达您的控制器方法并且请求从 servlet filter.chain 停止,并且推荐的架构在控制器内部使用 dto 并使用 LOMBOK 验证检查验证,所有业务逻辑都将服务类中的进程

标签: java spring spring-boot postman spring-restcontroller


【解决方案1】:

Customer 的验证似乎失败了。 我会

  1. 查看日志以了解错误详细信息
  2. 考虑为请求对象创建一个单独的类。您真的不想混合数据库相关和请求相关的问题。

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2018-08-07
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多