spring-responseentity未使用

093gszye  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(258)

对spring还不熟悉,所以我想返回一个400或201(创建的)带有rest端点,但是现在它只通过postman返回一个空的200响应。
sampleservice.java文件

@Service
public class SampleService {

    private SampleRepository sampleRepository;

    @Autowired
    public SampleService(SampleRepository sampleRepository) {
        this.sampleRepository = sampleRepository;
    }

    public ResponseEntity<Response> registerData(Data data) {
        Optional<SampleData> dataOptional = sampleRepository.findDataByName(data.getName());

        if(dataOptional.isPresent()) {
            // Returns blank 200 response
            return new ResponseEntity<>(
                    new Error(
                            "Bad Request",
                            "Data already exists."
                    ),
                    HttpStatus.BAD_REQUEST
            );
        }

        sampleRepository.save(data);

        // Returns blank 200 response
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(
                    // I haven't got far to creating a response, so do not mind the "Error".
                    new Error("Created", "Stand-in until created proper response")
                );
    }
}

响应.java

public interface Response {}

错误.java

public class Error implements Response {
    private String errorType;
    private String errorMessage;

    public Error(String errorType, String errorMessage) {
        this.errorType = errorType;
        this.errorMessage = errorMessage;
    }

    public String getErrorType() {
        return errorType;
    }

    public void setErrorType(String errorType) {
        this.errorType = errorType;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}

如果有人还需要什么,请告诉我,但这应该足够了。

ldioqlga

ldioqlga1#

如前所述,刚接触spring,忘记更改控制器层的返回类型:
samplecontroller.java文件

@PostMapping
public ResponseEntity<Response> createData(@RequestBody Data data) {
    return this.sampleService.registerData(data);
}

相关问题