[java] What to return if Spring MVC controller method doesn't return value?

I am using jQuery's $.getJSON() to make asynchronous calls to my simple Spring MVC backend. Most of the Spring controller methods look like this:

@RequestMapping(value = "/someURL", method = RequestMethod.POST)
public @ResponseBody SomePOJO getSomeData(@ModelAttribute Widget widget,
    @RequestParam("type") String type) {
    return someDAO.getSomeData(widget, type);
}   

I have things set up so that each controller returns the @ResponseBody as JSON, which is what the client-side expects.

But what happens when a request isn't supposed to return any content to the client-side? Can I have:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public @ResponseBody void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

If not, what's the appropriate syntax to use here?

This question is related to java jquery spring-mvc

The answer is


But as your system grows in size and functionality... i think that returning always a json is not a bad idea at all. Is more a architectural / "big scale design" matter.

You can think about returing always a JSON with two know fields : code and data. Where code is a numeric code specifying the success of the operation to be done and data is any aditional data related with the operation / service requested.

Come on, when we use a backend a service provider, any service can be checked to see if it worked well.

So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.


Here is example code what I did for an asynchronous method

@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void importDataFromFile(@RequestParam("file") MultipartFile file) 
{
    accountingSystemHandler.importData(file, assignChargeCodes);
}

You do not need to return any thing from your method all you need to use this annotation so that your method should return OK in every case

@ResponseStatus(value = HttpStatus.OK)

Yes, you can use @ResponseBody with void return type:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseBody
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

You can simply return a ResponseEntity with the appropriate header:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}

You can return "ResponseEntity" object. Using "ResponseEntity" object is very convenient both at the time of constructing the response object (that contains Response Body and HTTP Status Code) and at the time of getting information out of the response object.

Methods like getHeaders(), getBody(), getContentType(), getStatusCode() etc makes the work of reading the ResponseEntity object very easy.

You should be using ResponseEntity object with a http status code of 204(No Content), which is specifically to specify that the request has been processed properly and the response body is intentionally blank. Using appropriate Status Codes to convey the right information is very important, especially if you are making an API that is going to be used by multiple client applications.


There is nothing wrong with returning a void @ResponseBody and you should for POST requests.

Use HTTP status codes to define errors within exception handler routines instead as others are mentioning success status. A normal method as you have will return a response code of 200 which is what you want, any exception handler can then return an error object and a different code (i.e. 500).


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)