Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a redirect from a spring MVC @ExceptionHandler method

I want to have the following method:

@ExceptionHandler(MyRuntimeException.class)
public String myRuntimeException(MyRuntimeException e, RedirectAttributes redirectAttrs){//does not work
    redirectAttrs.addFlashAttribute("error", e);
    return "redirect:someView";
}

I get a:

java.lang.IllegalStateException: No suitable resolver for argument [1] type=org.springframework.web.servlet.mvc.support.RedirectAttributes]

Is there a way to perform a redirect from an @ExceptionHandler? Or maybe some way to circumvent this restriction?

EDIT:

I have modified my exception handler as follows:

@ExceptionHandler(InvalidTokenException.class)
public ModelAndView invalidTokenException(InvalidTokenException e, HttpServletRequest request) {
RedirectView redirectView = new RedirectView("signin");
return new ModelAndView(redirectView , "message", "invalid token/member not found");//TODO:i18n
}

This is the method that may throw the exception:

@RequestMapping(value = "/activateMember/{token}", method = RequestMethod.GET, produces = "text/html")
public String activateMember(@PathVariable("token") String token) {
    signupService.activateMember(token);
    return "redirect:memberArea/index";
}

The problem with my modified exception handler is that it systematically redirects me to the following URL:

http://localhost:8080/bignibou/activateMember/signin?message=invalid+token%2Fmember+not+found 

Instead of:

http://localhost:8080/bignibou/signin?message=invalid+token%2Fmember+not+found

EDIT 2:

Here is my modified handler method:

@ExceptionHandler(InvalidTokenException.class)
public String invalidTokenException(InvalidTokenException e, HttpSession session) {
session.setAttribute("message", "invalid token/member not found");// TODO:i18n
return "redirect:../signin";
}

The problem I now have is that the message is stuck in the session...

like image 257
balteo Avatar asked Feb 19 '13 16:02

balteo


People also ask

How do I redirect a spring boot to another URL?

We can use a name such as a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.

What is the use of redirect in Spring MVC?

Using the redirect prefix in your controller will generate a HTTP response with the 302 status code and the location header pointing to the redirection URL. The browser will then redirect to that URL (model exposed in the first request will be lost, and the browser URL will be the second one). Save this answer.

What is the difference between ControllerAdvice and RestControllerAdvice?

The differences between @RestControllerAdvice and @ControllerAdvice is : @RestControllerAdvice = @ControllerAdvice + @ResponseBody . - we can use in REST web services. @ControllerAdvice - We can use in both MVC and Rest web services, need to provide the ResponseBody if we use this in Rest web services.

What is true about the @ExceptionHandler and @ControllerAdvice annotations?

The@ControllerAdvice annotation allows us to consolidate our multiple, scattered @ExceptionHandlers from before into a single, global error handling component. The actual mechanism is extremely simple but also very flexible: It gives us full control over the body of the response as well as the status code.


3 Answers

Note that this is actually supported out-of-the-box by Spring 4.3.5+ (see SPR-14651 for more details).

I've managed to get it working using the RequestContextUtils class. My code looks like this

@ExceptionHandler(MyException.class)
public RedirectView handleMyException(MyException ex,
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
    String redirect = getRedirectUrl(currentHomepageId);

    RedirectView rw = new RedirectView(redirect);
    rw.setStatusCode(HttpStatus.MOVED_PERMANENTLY); // you might not need this
    FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
    if (outputFlashMap != null){
        outputFlashMap.put("myAttribute", true);
    }
    return rw;
}

Then in the jsp page I simply access the attribute

<c:if test="${myAttribute}">
    <script type="text/javascript">
      // other stuff here
    </script>
</c:if>

Hope it helps!

like image 187
mericano1 Avatar answered Oct 01 '22 22:10

mericano1


You could always forward then redirect (or redirect twice).. First to another request mapping where you have normal access to RedirectAttributes, then again to your final destination.

    @ExceptionHandler(Exception.class)
    public String handleException(final Exception e) {

        return "forward:/n/error";
    }

    @RequestMapping(value = "/n/error", method = RequestMethod.GET)
    public String error(final RedirectAttributes redirectAttributes) {

        redirectAttributes.addAttribute("foo", "baz");
        return "redirect:/final-destination";
    }
like image 39
Michael Peterson Avatar answered Oct 02 '22 00:10

Michael Peterson


I am looking at the JavaDoc and I don't see where RedirectAttributes is a valid type that is accepted.

like image 42
CodeChimp Avatar answered Oct 01 '22 22:10

CodeChimp