Return HTTP 204 on null with spring @RestController
You can use the @ResponseStatus annotation. This way you can have a void method and you don't have to build a ResponseEntity.
@DeleteMapping(value = HERO_MAPPING)@ResponseStatus(value = HttpStatus.NO_CONTENT)public void delete(@PathVariable Long heroId) { heroService.delete(heroId);}
BTW returning 200 when the object exists and 204 otherwise it's a bit unusual regarding API REST design. It's common to return a 404 (not found) when the requested object is not found. And this can be achieved using a ControllerAdvice.
In Spring REST it's better to handle Exceptions with a Exception handler instead of putting logic to decide the response status, etc. This is an example using the @ControllerAdvice annotation: http://www.jcombat.com/spring/exception-handling-in-spring-restful-web-service
Of course yes.
Option 1 :
@RestControllerpublic class RepoController { @RequestMapping(value = "/document/{id}", method = RequestMethod.GET) public Object getDocument(@PathVariable long id, HttpServletResponse response) { Object object = getObject(); if( null == object ){ response.setStatus( HttpStatus.SC_NO_CONTENT); } return object ; }}
Option 2 :
@RestControllerpublic class RepoController { @RequestMapping(value = "/document/{id}", method = RequestMethod.GET) public Object getDocument(@PathVariable long id) { Object object = getObject(); if ( null == object ){ return new ResponseEntity<Void>(HttpStatus.NO_CONTENT); } return object ; }}
Might have typos, but you get the concept.
I solved this problem with a filter. It's global and simple.
package your.package.filter;import org.springframework.http.HttpStatus;import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class NoContentFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(httpServletRequest, httpServletResponse); if (httpServletResponse.getContentType() == null || httpServletResponse.getContentType().equals("")) { httpServletResponse.setStatus(HttpStatus.NO_CONTENT.value()); } }}
and add the following in your web.xml
<filter> <filter-name>restNoContentFilter</filter-name> <filter-class>your.package.filter.NoContentFilter</filter-class></filter><filter-mapping> <filter-name>restNoContentFilter</filter-name> <url-pattern>/rest/*</url-pattern></filter-mapping>