Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

java - Spring - ResponseEntity not being used

New to Spring, so I want to return either a 400 or a 201 (Created) with a REST endpoint, but right now it only returns an empty 200 response via Postman.

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

Response.java

public interface Response {}

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

If anyone needs anything else, let me know, but this should be enough to cover.

question from:https://stackoverflow.com/questions/65844701/spring-responseentity-not-being-used

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As I stated, new to Spring, and forgot to change the return type for my controller layer:

SampleController.java

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...