2013-07-24 69 views
0

我正在使用spring mvc進行一些練習編程,我決定做一個關於內容協商的例子。查看不同輸出格式時的內容協商

我開始用一個URI「/產品」:

  • 當我問/products.json它返回我JSON,其中我對
  • 開心的時候我問/products.xml它返回正確的XML,我很高興
  • 當我要求的HTML視圖(/產品),目前我只顯示一個簡單的HTML表的產品,但如果我想包括額外的動態內容像標籤雲或類似產品(與產品無關的東西)的HTML頁面?

下面是我的控制器方法的代碼。

@RequestMapping(method = RequestMethod.GET) 
    public ModelAndView getAllProducts(){ 
     ModelAndView result = new ModelAndView("index"); 
     GenericListElementWrapper<Product> products = new GenericListElementWrapper<Product>(); 

     products.setList(productDao.getAll()); 
     ModelMap modelMap = new ModelMap(); 
     modelMap.addAttribute("products",products); 
     result.addAllObjects(modelMap); 

     return result; 
    } 

我想什麼來實現如下:有把我的單控制器的方法,但

  • 的方式HTML視圖將有額外的內容

的想法,我曾經是:

  • 也許使用servlet過濾器來豐富Mod elAndView僅用於text/html mimetype?但是,你是這樣做的所有html請求可能是不受歡迎的?

  • 目前我解釋自己的方式感覺就像我想要一個完整的呈現HTML視圖發送到客戶端。也許我錯誤地看着這個問題,我應該考慮在通過javascript加載頁面之後檢索額外內容的方式?

那麼有可能實現我的預期解決方案嗎?另一部分是我的預期解決方案在實踐中是否確實需要:P

回答

1

一種可能性是添加攔截器並將其映射到您選擇的路徑。執行控制器上的處理程序後,interceptor.postHandle提供訪問ModelAndView。可以添加一些額外的東西。

<mvc:interceptors> 
    <mvc:interceptor> 
     <mvc:mapping path="/my/path"/> 
     <ref bean="enhancedContentInterceptor" /> 
    </mvc:interceptor> 
</mvc:interceptors> 

@Component 
public class EnhancedContentInterceptor implements HandlerInterceptor { 

    public boolean preHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler) throws Exception { 

     return true; 
    } 

    public void postHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler, 
      ModelAndView modelAndView) throws Exception { 

     if (request.getContentType().equals("text/html")) { 
      modelAndView.addObject("tags", tagProvider.getTags()); 
     } 
    } 

    public void afterCompletion(HttpServletRequest request, 
      HttpServletResponse response, Object handler, Exception ex) 
      throws Exception {} 

    } 
}