Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward in Spring MVC interceptor

I defined view resolver like this:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

and I had a interceptor, when some conditions not pass, I want to forward to a jsp page, I implement like this:

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/jsp/info.jsp");
requestDispatcher.forward(request, response);

Above, the page that I want to forward is hard code, I didn't want to do like that, is there any approach that I can get the page from the view resolver?

like image 341
Rocky Hu Avatar asked Nov 26 '25 19:11

Rocky Hu


2 Answers

If you wanted to forward to a view from a postHandle it would have been easier because in postHandle you have full access to the ModelAndView.

It is also possible in a preHandle method, thanks to the ModelAndViewDefiningException, that allows you to ask spring to do itself the forward from anywhere in a handler processing.

You can use it that way :

public class ForwarderInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // process data to see whether you want to forward
        ...
            // forward to a view
            ModelAndView mav = new ModelAndView("forwarded-view");
            // eventually populate the model
            ...
            throw new ModelAndViewDefiningException(mav);
        ...
        // normal processing
        return true;
    }

}
like image 109
Serge Ballesta Avatar answered Nov 28 '25 15:11

Serge Ballesta


If we consider you're using SpringMVC and using controllers and you want to redirect to a info.jsp the code should looks like this :

@Controller
public class InfoController {

 @RequestMapping(value = "/info", method = RequestMethod.GET)
 public String info(Model model) {
     // TODO your code here
     return "info";
 }
}
like image 44
Abderrazak BOUADMA Avatar answered Nov 28 '25 17:11

Abderrazak BOUADMA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!