Use spring Response Entity to process HTTP return requests

Usually, in the context of front-end and back-end separation, our back-end services are usually returned to the front-end formatted data, such as Json. At the beginning, we used JSON package to produce a JSON string, which is customized with some API s of http protocol.

            spring has evolved to the present day and has packaged generic processing classes: ResponseEntity, which are inherited from HttpEntity
 public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;

/**
 * Create a new {@code ResponseEntity} with the given status code, and no body nor headers.
 * @param status the status code
 */
public ResponseEntity(HttpStatus status) {
    this(null, null, status);
}

/**
 * Create a new {@code ResponseEntity} with the given body and status code, and no headers.
 * @param body the entity body
 * @param status the status code
 */
public ResponseEntity(@Nullable T body, HttpStatus status) {
    this(body, null, status);
}
            And it has been extended to deal with the status code, header, body and other data in the process of http request.

ResponseEntity is a generic type. Therefore, we can use any type as the response subject:

@Controller
public class XXXController{br/>@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello !", HttpStatus.OK);
}

Here the string "Hello World!" is returned to the REST end as a string.

We can set HTTP headers:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");

return new ResponseEntity<>(
"Custom header set", headers, HttpStatus.OK);
}

Set custom headers:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
return ResponseEntity.ok()
.header("Custom-Header", "foo")
.body("Custom header set")

If an object is placed:

@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>(new User('jdon'), HttpStatus.OK);
}

The return is a JSON string:

[ { 'name': 'jdon'}]

The following is a list of JSON returned objects:

public ResponseEntity<List<ProcessDef>> repositoryProcessDefinitionsGet() {
return new ResponseEntity<>(processDefRepo.findAll(), HttpStatus.FOUND);
}

The above is to manipulate the response flexibly in the code through the ResponseEntity object, but in general we just want to return a normal response with data, so just use the @ annotation.

@ResponseBody
With the @Controller annotation at the class level, the @ResponseBody annotation tells the returned object to be serialized automatically into JSON and passed back to the controller's HttpResponse object.

@Controller
public class XXXController{

@ResponseBody
public User postResponseController(@RequestBody LoginForm loginForm) {
return new User("Thanks For Posting!!!");
}

The client JSON string is returned:

[ { 'name': Thanks For Posting!!!"}]

When @RestController annotates the class, we don't need to use @ResponseBody anymore. We can return the object directly and use ResponseStatus to return the status code!

@ResponseStatus
ResponseStatus only specifies the return status, but it only needs to be labeled in the method. It is simple, and the status code is separated from the return type, so it is clear. We rewrite the above code to return the list of objects using ResponseStatus as follows, noting the class level @RestController:

@RestController
public class XXXController{

@ResponseStatus(HttpStatus.FOUND)
public User postResponseController() {
return new User("Thanks For Posting!!!");
}

This also returns the client JSON string:

[ { 'name': Thanks For Posting!!!"}]

Such code is more business-focused.

Direct Manipulation Response
Spring also allows us direct access to the javax.servlet.http.HttpServletResponse object; we just need to declare it as a method parameter:

@GetMapping("/manual")
public void manual(HttpServletResponse response) throws IOException {
response.setHeader("Custom-Header", "foo");
response.setStatus(200);
response.getWriter().println("Hello World!");
}

Because Spring provides abstraction and additional functionality on top of the underlying implementation, if you manipulate the response directly in this way, you will lose a lot of the convenience Spring provides.

Example code:

import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.constraints.*;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-03-09T21:32:18.308+08:00")

@Api(value = "tag", tags={ "tag", }, description = "the tag API")
public interface TagApi {

@ApiOperation(value = "Get a list of problem summary Tags", notes = "get_issue_summary_tags", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = OperateResult.class),
    @ApiResponse(code = 500, message = "system error", response = Void.class) })

@RequestMapping(value = "/tag/{issue_summary_key}/tags",
    produces = { "application/json" }, 
    method = RequestMethod.GET)
default ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "project key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
    // do some magic!
    return new ResponseEntity<OperateResult>(HttpStatus.OK);
}

@ApiOperation(value = "Get a list of problem profile tag values", notes = "get_tag_values", response = OperateResult.class, tags={ "tag", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = OperateResult.class),
    @ApiResponse(code = 500, message = "system error", response = Void.class) })

@RequestMapping(value = "/tag/{issue_summary_key}/tag_value/{tag_type}",
    produces = { "application/json" }, 
    method = RequestMethod.GET)
default ResponseEntity<OperateResult> getTagValues(@NotNull @ApiParam(value = "project key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey, @ApiParam(value = "Tag type app: application device: equipment server_name:Service name level:level logger:Journal os: system user: user url:URL transaction:Thing", required = true) @PathVariable("tag_type") String tagType, @NotNull @Min(1) @ApiParam(value = "page", required = true, defaultValue = "1") @RequestParam(value = "page_number", required = true, defaultValue = "1") Integer pageNumber, @NotNull @Min(1) @ApiParam(value = "Number of display bars per page", required = true, defaultValue = "10") @RequestParam(value = "page_size", required = true, defaultValue = "10") Integer pageSize) {
    // do some magic!
    return new ResponseEntity<OperateResult>(HttpStatus.OK);
}

}

@Controller
public class TagApiController implements TagApi {

private final static Logger logger = LoggerFactory.getLogger(TagApiController.class);

@Autowired
private TagService tagService;

@Override
public ResponseEntity<OperateResult> getIssueSummaryTags(@NotNull @ApiParam(value = "project key", required = true) @RequestParam(value = "project_key", required = true) String projectKey, @ApiParam(value = "issue_summary_key", required = true) @PathVariable("issue_summary_key") String issueSummaryKey) {
    OperateResult operateResult = new OperateResult();
    try {
        Preconditions.checkArgument(StringUtils.isNotBlank(projectKey));
        Preconditions.checkArgument(StringUtils.isNotBlank(issueSummaryKey));
        List<TagDetail> tagValueArrayList = tagService.getIssueSummaryTagList(projectKey, issueSummaryKey);
        operateResult = OperateResult.success(tagValueArrayList);
        return new ResponseEntity<OperateResult>(operateResult,HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api getIssueSummaryTags error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR,e);
        return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Keywords: Programming JSON Spring REST

Added by smiley_kool on Thu, 16 May 2019 16:08:42 +0300