How to use send.redirect() while working with Spring MVC

16,731

You need to add redirect: prefix in the view name, the code for redirect will look like:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
   public String redirect() {

      return "redirect:finalPage";
   }

OR

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView redirect() {

  return new ModelAndView("redirect:finalPage");
}

You may get a detail description from here: enter link description here

Share:
16,731
bkuriach
Author by

bkuriach

Updated on June 04, 2022

Comments

  • bkuriach
    bkuriach almost 2 years

    I was trying to redirect to a dynamic page from Interceptors and Handler Mapping program. I have already defined a controller which handles and redirects (/hello.htm) through model (I have only this controller in my program). Until this point it is working fine. Apart from this, I registered a handler which will redirect to a page once it satisfies some condition.

    public class WorkingHoursInterceptor extends HandlerInterceptorAdapter  {
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("In Working Hours Interceptor-pre");
        Calendar c=Calendar.getInstance();
        if(c.get(Calendar.HOUR_OF_DAY)<10||c.get(Calendar.HOUR_OF_DAY)>20){
            response.sendRedirect("/WEB-INF/jsp/failure.jsp");
                            return false;
        }
        return true;
    ..............
    ..............
    } 
    

    But once it comes to response.sendRedirect, it is showing resource not found even though the mentioned page is present. I tried to redirect to "WEB-INF/jsp/hello.jsp" as well but keeps showing the same error. If the condition in the interceptor is not satisfied, the program works fine.

    Below is shown the only controller present in the program.

    @Controller
    public class MyController {
    @RequestMapping("/hello.htm")
    public ModelAndView sayGreeting(){
        String msg="Hi, Welcome to Spring MVC 3.2";
        return new ModelAndView("WEB-INF/jsp/hello.jsp","message",msg);
    
        }
    
    }
    

    (The controller for handling hello.html works fine if I change the interceptor condition)

    Instead of redirecting, if I just print a message in the console, the program works fine. But once it comes to redirect it shows the error. Do I need to specify a separate controller to handle this request? Will this redirection request go to the dispatcher-servlet?