How do I get a Spring 3.0 controller to trigger a 404?
I have a controller with @RequestMapping(value = \"/**\", method = RequestMethod.GET)
and for som
If your controller method is for something like file handling then ResponseEntity
is very handy:
@Controller
public class SomeController {
@RequestMapping.....
public ResponseEntity handleCall() {
if (isFound()) {
return new ResponseEntity(...);
}
else {
return new ResponseEntity(404);
}
}
}
Starting from Spring 5.0, you don't necessarily need to create additional exceptions:
throw new ResponseStatusException(NOT_FOUND, "Unable to find resource");
Also, you can cover multiple scenarios with one, built-in exception and you have more control.
See more:
Rewrite your method signature so that it accepts HttpServletResponse
as a parameter, so that you can call setStatus(int)
on it.
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments
This is a bit late, but if you are using Spring Data REST then there is already org.springframework.data.rest.webmvc.ResourceNotFoundException
It also uses @ResponseStatus
annotation. There is no need to create a custom runtime exception anymore.
Also if you want to return 404 status from your controller all you need is to do this
@RequestMapping(value = "/somthing", method = RequestMethod.POST)
@ResponseBody
public HttpStatus doSomthing(@RequestBody String employeeId) {
try{
return HttpStatus.OK;
}
catch(Exception ex){
return HttpStatus.NOT_FOUND;
}
}
By doing this you will receive a 404 error in case when you want to return a 404 from your controller.
you can use the @ControllerAdvice to handle your Exceptions , The default behavior the @ControllerAdvice annotated class will assist all known Controllers.
so it will be called when any Controller you have throws 404 error .
like the following :
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
@ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
and map this 404 response error in your web.xml , like the following :
<error-page>
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
Hope that Helps .