2015-08-31 45 views
0

我想顯示一個包含所有產品及其折扣的頁面。 productService爲我提供了所有產品,並返回了DTO(沒有折扣或包含任何折扣) discountService爲我帶來了每種產品的折扣,並使用動態名稱將這些折扣添加到modelAndView中。Spring MVC + JSP:動態對象和變量表達式

@RequestMapping("/all") 
public ModelAndView getAll(){ 
    List<ProductDTO> products = productService.findAll(); 
    ModelAndView modelAndView = new ModelAndView("products/all", "products", products); 
    for(ProductDTO productDTO : products){ 
     List<DiscountDTO> discountDTOs = discountService.findAllDiscountsForProductApplicableForUser(productDTO.getId(), userService.getCurrentLoggedInUser()); 
     modelAndView.addObject("product" + productDTO.getId() + "_applicableDiscounts", discountDTOs); 
    } 
    return modelAndView; 
} 

我似乎無法找到我怎麼能在我的JSP頁面存取權限這些,使用EL $ {} product5_applicableDiscounts完美的作品,$ { '產品' + product.id + '_ applicableDiscounts'}被評爲一個字符串。

任何knwos如何做到這一點?

+0

任何特殊的理由來顯示唯一字符串中的信息?也許你可以使用Map來解決 – Kratul

回答

0

您可以使用

${requestScope['product'+product.id+'_applicableDiscounts']} 

不過,我覺得它難看。

爲什麼不將折扣添加到ProductDTO呢?或者創建一個包含ProductDTO實例及其適用折扣的新類作爲bean屬性?

0

我想你可以使用Spring的eval標籤

<spring:eval expression="product${product.id}_applicableDiscounts" var="discounts"/> 

,然後你可以使用「折扣」變量。