2016-02-05 145 views
0

在我的Spring MVC項目中,我添加了一個攔截器類來檢查重定向是否被觸發。如何簽入攔截器是否觸發重定向

這裏是我的控制器類:

@Controller 
public class RedirectTesterController { 

    @RequestMapping (value="/page1") 
    public String showPage1(){ 

     return "page1"; 
    } 

    @RequestMapping (value="/submit1") 
    public String submitPage1(){ 

     return "redirect:/page2"; 
    } 

    @RequestMapping (value="/page2") 
    public String showPage2(){ 

     return "page2"; 
    } 

} 

所以,如果我打電話例如

本地主機:8080/MyContext/submit1

執行方法 「submitPage1」。

現在 - 服務器告訴客戶端,調用

本地主機:8080/MyContext/2頁

這也是工作。

所以 - 我想在執行方法「submitPage1」之後進入該過程。 在我看來,httpResponse中應該有一些命令/命令,我可以問。

爲了檢查,我在方法中的攔截器類中做了一個斷點:「postHandle」 - 從那時起,我不知道如何繼續。 我試圖讀取outputStream - 但這樣做會崩潰我的應用程序。 (導致一個異常 - > outputStream已被調用..)。

這難道不是一個簡單的解決方案嗎?

回答

0

下面的示例演示如何測試一個視圖是一個redirect

@Configuration 
public class MvcConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
     registry.addInterceptor(new HandlerInterceptorAdapter() { 
      @Override 
      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
            ModelAndView modelAndView) throws Exception { 
       if (modelAndView != null && StringUtils.startsWithIgnoreCase(modelAndView.getViewName(), "redirect:")) { 
        // handle redirect... 
       } 
      } 
     }); 
    } 
} 

見:HandlerInterceptorAdapterStringUtils

Spring MVC的文檔:Intercepting requests with a HandlerInterceptor