Reputation: 3428
I am using an exception class for @ResponseStatus
, but I am not able to figure out how do I send redirect URL in case of 301 Permanently Moved error ?
Exception class:
@ResponseStatus(value = HttpStatus.MOVED_PERMANENTLY)
public class ResourceMovedPermanentlyException extends RuntimeException{
}
Upvotes: 0
Views: 1266
Reputation: 4792
The question is not very clear. I suppose you want to redirect to a page in case of ResourceMovedPermanentlyException
being thrown. In that case you could use the ExceptionHandler
annotation:
@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final Exception e) {
return "redirect:/the/target/page";
}
Alternative implementation:
@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final RuntimeException e,
final HttpServletRequest request, // this can be omitted if not needed
final HttpServletResponse response) throws IOException
response.sendRedirect("/the/page/or/url/you/need/to/redirect");
}
You also could store the redirect URL into the exception:
@ExceptionHandler(ResourceMovedPermanentlyException.class)
public String handleException(final ResourceMovedPermanentlyException e,
final HttpServletResponse response) throws IOException
response.sendRedirect(e.getRedirectUrl());
}
See the ExceptionHandler JavaDoc for more details about the options available for the exception handler method.
Upvotes: 1
Reputation: 64059
I don't think you can add the url with the simplified exception handling you are using.
Check out vzamanillo's solution (use it in a class that is annotated with @ControllerAdvice
and a method annotated with @ExceptionHandler
).
For the whole story of Spring MVC exception handling check out this blog post
Upvotes: 1
Reputation: 10534
You can use a Spring's RedirectView
RedirectView rv = new RedirectView(url);
rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
rv.setUrl(url);
ModelAndView mv = new ModelAndView(rv);
return mv;
Upvotes: 3