1
votes

I am very new to Spring. I have a REST api written in Spring, but I don't know how to return a JSON response with a custom http response code.

I return a JSON response as follows:

public String getUser(String id){

...
return jsonObj;
}

But it always displays 200 http ok status code.

Here are my questions:

How can I synchronize the response JSON and HTTP code?

How is it possible to return JSON response and custom HTTP code in void function?

2

2 Answers

2
votes

How I do it

Here is how I do JSON returns from a Spring Handler method. My techniques are somewhat out-of-date, but are still reasonable.

Configure Jackson Add the following to the spring configuration xml file:

<bean name="jsonView"
    class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>

With that, Spring will convert return values to JSON and place them in the body of the response.

Create a utility method to build the ResponseEntity Odds are good that you will have multiple handler methods. Instead of boilerplate code, create a method to do the standard work. ResponseEntity is a Spring class.

protected ResponseEntity<ResponseJson> buildResponse(
    final ResponseJson jsonResponseBody,
    final HttpStatus httpStatus)
{
    final ResponseEntity<ResponseJson> returnValue;

    if ((jsonResponseBody != null) &&
        (httpStatus != null))
    {
        returnValue = new ResponseEntity<>(
            jsonResponseBody,
            httpStatus);
    }

    return returnValue;
}

Annotate the handler method

@RequestMapping(value = "/webServiceUri", method = RequestMethod.POST)

you can also use the @PostMethod annotation

@PostMethod("/webServiceUri")

Return ResponseEntity from the handler method Call the utility method to build the ResponseEntity

public ResponseEntity<ResponseJson> handlerMethod(
    ... params)
{
    ... stuff

    return buildResponse(json, httpStatus);
}

Annotate the handler parameters Jackson will convert from json to the parameter type when you use the @RequestBody annotation.

public ResponseEntity<ResponseJson> handlerMethod(
    final WebRequest webRequest,
    @RequestBody final InputJson inputJson)
{
    ... stuff
}

A different story

You can use the @JsonView annotation. Check out the Spring Reference for details about this. Browse to the ref page and search for @JsonView.

5
votes

Use @ResponseStatus annotation:

@GetMapping
@ResponseStatus(HttpStatus.ACCEPTED)
public String getUser(String id) {...}

Alternative way: If you want to decide programmatically what status to return you can use ResponseEntity. Change return type of a method to ResponseEntity<String> and you'll be offered with a DSL like this:

ResponseEntity
        .status(NOT_FOUND)
        .contentType(TEXT_PLAIN)
        .body("some body");