Spring-MVC controller redirect to “previous” page?

后端 未结 7 984
无人共我
无人共我 2021-01-31 18:34

Let\'s say I\'ve got a form for editing the properties of a Pony, and in my web application there are multiple places where you can choose to edit a Pony. For instance, in a li

7条回答
  •  情歌与酒
    2021-01-31 19:07

    You can also keep track of the ModelAndView (or just the view) that have been last presented to the user with an interceptor. This example keeps track of only the last model and view, but you could use a list to navigate back more levels.

    package com.sample;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class LastModelAndViewInterceptor extends HandlerInterceptorAdapter {
    
        public static final String LAST_MODEL_VIEW_ATTRIBUTE = LastModelAndViewInterceptor.class.getName() + ".lastModelAndView";
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            request.getSession(true).setAttribute(LAST_MODEL_VIEW_ATTRIBUTE, modelAndView);
            super.postHandle(request, response, handler, modelAndView);
        }
    
    }
    

    With Spring XML configuration:

    
        
            
        
    
    

    And then use the following code to get back to that view in a controller:

    ModelAndView mv = (ModelAndView)request.getSession().getAttribute(LastModelAndViewInterceptor.LAST_MODEL_VIEW_ATTRIBUTE);
    return mv;
    

提交回复
热议问题