Return status code 302 to Spring MVC Controller

I am developing a Spring MVC application and I need to check a specific condition in my controller. If this is true, I should return a status code of 302. This is something like this:

@RequestMapping(value = "/mypath.shtml", method = RequestMethod.GET)
public ModelAndView pageHandler(@Valid MyForm form, BindingResult result, HttpServletRequest request,
        Locale locale) throws PageControllerException, InvalidPageContextException, ServiceException {

    if (someCondition){
        // return 302 status code
    }
    else{
        // Do some stuff
    }
}

What is the best way to do this?

Thank you in advance

+4
source share
3 answers

I finally managed to do this using @ResponseStatusas below:

fooobar.com/questions/40704 / ...

UPDATE

Here is how I did it:

@ResponseStatus(value = HttpStatus.MOVED_TEMPORARILY)
public class MovedTemporarilyException extends RuntimeException {

    // ...
}

@RequestMapping(value = "/mypath.shtml", method = RequestMethod.GET)
public ModelAndView pageHandler(@Valid MyForm form, BindingResult result, HttpServletRequest request,
        Locale locale) throws PageControllerException, InvalidPageContextException, ServiceException {

    if (someCondition){
        throw new MovedTemporarilyException();
    }
    else{
        // Do some stuff
    }
}
+5
source

The following code will execute:

if (someCondition){
    return new ModelAndView("redirect:" + someUrl)
}
else{
        // Do some stuff
}
+3
source

org.springframework.web.servlet.view.RedirectView . URL.

The previous answers worked for me, but the Location header for the redirect included model attributes added by some mail interceptor methods.

return a new RedirectView (newLocationVia302, true, true, false);

+1
source

Source: https://habr.com/ru/post/1543053/


All Articles