简体   繁体   English

Spring Boot 响应正文在 PostMan 中显示为空

[英]Spring boot response body is showing empty in PostMan

I am using @Valid annotation to validate some of my model properties.我正在使用 @Valid 注释来验证我的一些模型属性。 It is working as expected, if any data is not provided as per the expectation it is throwing back 400 Bad Request error.它按预期工作,如果未按预期提供任何数据,则会返回 400 Bad Request 错误。 But the response body is always coming as empty.但是响应体总是空的。

My Controller Class我的控制器类

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bnpp.leavemanagement.exception.DepartmentNotFoundException;
import com.bnpp.leavemanagement.exception.EmployeeAlreadyExistsException;
import com.bnpp.leavemanagement.exception.EmployeeNotFoundException;
import com.bnpp.leavemanagement.model.EmployeeModel;
import com.bnpp.leavemanagement.service.EmployeeService;

@RestController
@Validated
@RequestMapping("/employee")
public class EmployeeController 
{
    @Autowired
    EmployeeService empService;
    
    
    @PostMapping("/create")
    public ResponseEntity<EmployeeModel> createEmployee(@RequestBody @Valid EmployeeModel empNew) throws  EmployeeAlreadyExistsException, DepartmentNotFoundException, EmployeeNotFoundException
    {
        EmployeeModel resEmp = empService.addEmployee(empNew);
        return new ResponseEntity( resEmp, HttpStatus.CREATED);
    }

Model Class Property模型类属性

  @JsonProperty("firstName")
  @NotEmpty(message = "FirstName cannot be empty")
  private String firstName = null;

application.properties应用程序属性

spring.datasource.url=jdbc:h2:mem:leavemgmt
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

server.port=8443

server.ssl.key-alias=leavemanagement
server.ssl.key-store=classpath:leavemanagement.jks
server.ssl.key-store-type=JKS
server.ssl.key-store-password=password

server.error.include-message=always
server.error.include-binding-errors=always
server.error.include-exception=true
server.error.include-stacktrace=always

邮递员回复

Please help me on what to be done to get the response body in Postman on any validation failure.请帮助我了解在任何验证失败时如何在 Postman 中获取响应正文。

You need to add your errors in your response using BindingResult like this in your controller:您需要在您的控制器中使用BindingResult在您的响应中添加您的错误:

 public ResponseEntity<EmployeeModel> createEmployee(@Valid @RequestBody EmployeeModel empNew,BindingResult bindingResult)
{
  if(bindingResult.hasErrors())
   {
     for(FieldError fieldError : bindingResult.getFieldErrors()) {
            //you can define your ErrorMOdel dto here and add  
          //fieldError properties then add the whole errorList in 
          //your response.
         //Finally, return the response from here
        }
   }

  //if there is no errors in your request: execute this part:
   EmployeeModel resEmp = empService.addEmployee(empNew);
        return new ResponseEntity( resEmp, HttpStatus.CREATED);

}

Update according to your need:根据您的需要更新:
You can define your EmployeeModel in this way:您可以通过以下方式定义EmployeeModel

public class EmployeeModel<T> implements Serializable
{
  //your previously defined entities here
     private List<T> errorList;  //this is new one to show errors

    //constructors, setters, getters
}

Now, when you get error, replace the previous code with this:现在,当您遇到错误时,将之前的代码替换为:

if(bindingResult.hasErrors())
       {
         EmployeeModel response= new EmployeeModel();
         for(FieldError fieldError : bindingResult.getFieldErrors()) 
            {
               response.setErrorList(bindingResult.getFieldErrors());
            }
           return new ResponseEntity( response, 
            HttpStatus.BAD_REQUEST);
       }

Further improvisation you can carry on:您可以进行进一步的即兴创作:
You can add another field as status in your EmpoloyeeModel , status will be set as success when there is no error, otherwise, set to error ie employeeModel.setStatus("success") or.setStatus("error") depending on the situation Better, write a generic Response class to hold all type of response like this:您可以在您的EmpoloyeeModel添加另一个字段作为状态,没有错误时status将设置为success ,否则根据情况设置为erroremployeeModel.setStatus("success") or.setStatus("error")更好, 编写一个通用的 Response 类来保存所有类型的响应,如下所示:

@Data
@NoArgsConstructor
public class ServiceResponse<T> implements Serializable {
private HttpStatus status; //OK_Failure
private StatusCode statusCode; //code
private T body;
private List<T> errorList;
}

Let me know if you face any problem regarding this.如果您在这方面遇到任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用春天起动的空的肥皂邮差反应 - Empty soap postman response using spring boot @ApiResponse 响应体为空(Spring Boot) - @ApiResponse with empty response body (Spring Boot) Spring 引导 GET 请求给出 200 OK 状态,但 Postman 返回“ø”作为响应主体 - Spring Boot GET Request gives 200 OK status, but Postman returns "ø" as response body response.body()。getBasketShopList为空,但Postman中的API JSON不为空 - response.body().getBasketShopList is empty, but API JSON in Postman is not empty 如果我只是在 Spring Boot 中返回一个 Java 实例数组,那么 http 响应正文中有一个空数组 - There is an empty array in the http response body if I just return an array of Java Instances in Spring Boot ResponseBody 正在打印空体以进行弹簧启动测试 - ResponseBody is printing empty body for spring boot test Spring 引导在站点发送时拒绝正文,但不与 postman - Spring boot rejects body when sent by site but not with postman Spring Boot WebSocket - 向 CONNECT 响应添加正文 - Spring Boot WebSocket - Adding body to the CONNECT response 将响应主体添加到 Spring 启动执行器 - Adding response body to Spring Boot Actuator 是否可以在 spring 引导中读取响应正文? - Is it possible to read the body of a response in spring boot?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM