简体   繁体   中英

Restful Webservice string response

I have an endpoint where it supposes to sends a string as a response. My question is do I need to use to response Entity to send string response or just return the string to the consumer?

@GetMapping(value = "/word")
public String getWord() {
    String response = "webservice";
    return response;
}

Second approach:

@GetMapping(value = "/word", produces ={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> getWord() {
    String response = "webservice";
    return new ResponseEntity<>(response, HttpStatus.OK);
}

What is the correct approach to send just a string or use response entity?

What is the correct approach to send just a string or use response entity?

The Spring MVC documentation lists a number of types that can be returned from controller methods.

As I previously answered here and here , ResponseEntity<T> represents the entire HTTP response . Besides the body , its API allows you to set headers and a status code to the response.

Returning just a bean instance or a string is fine but doesn't give you much flexibility: In the future, if you need to add a header to the response or modify the status code, for example, you need to change the method return type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM