Return a 302 status code in Spring MVC Controller

14,387

Solution 1

I finally managed to do it using @ResponseStatus, as shown here:

https://stackoverflow.com/a/2067043/2982518

UPDATE

This is the way I finally 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
    }
}

Solution 2

The following code will do:

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

Solution 3

org.springframework.web.servlet.view.RedirectView has a few simple parameters. One of the parameters removes the model attributes from the URL.

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

return new RedirectView(newLocationVia302, true, true, false);
Share:
14,387
Genzotto
Author by

Genzotto

Web developer and enthusiastic about Java and NodeJS

Updated on July 12, 2022

Comments

  • Genzotto
    Genzotto almost 2 years

    I am developing a Spring MVC app, and I need to check in my controller a certain condition. In case it were true, I have to return a 302 status code. It's 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
        }
    }
    

    Which is the best way to do this?

    Thank you very much in advance