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

I tried to redirect to a dynamic page from the Handler interceptors and handlers program. I already defined a controller that processes and redirects (/hello.htm) through the model (I only have this controller in my program). Until this moment, it works fine. In addition, I registered a handler that will be redirected to the page if 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 as soon as it comes to response.sendRedirect , it shows a resource that is not found, even if the specified page is present. I also tried redirecting to "WEB-INF/jsp/hello.jsp" , but keeps showing the same error. If the condition in the interceptor is not satisfied, the program works fine.

Below is 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 the message in the console, the program works fine. But when it comes to redirection, it shows an error. Do I need to specify a separate controller to handle this request? Will this redirect request be sent to the servlet dispatcher?

+5
source share
1 answer

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

 @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 can get a detailed description from here: enter the link here

+4
source

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


All Articles