我正在创建一个购物车应用程序来学习Spring MVC。我想在多个页面中显示所有类别和子类别的列表。即;主页,产品页面,分类页面。如何在Spring MVC中存储共享对象以用于多个JSP?
在主页控制器中,我检索类别,子类别和特色产品的列表并将它们传递到主页。
@Controller
public class CatalogController {
@Autowired
private CategoryConfigService categoryConfigurationService;
@Autowired
private ProductConfigService productConfigurationService;
private static final Logger logger = LoggerFactory
.getLogger(CatalogController.class);
/**
* Catalog Controller method which retrieves the information required in the
* application home page(Categories,SubCategories)
*
* @return Home Page View
*/
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String returnHomePage(Model model) {
logger.info("Processing information for home page");
List<Category> categoriesList = categoryConfigurationService
.getAllCategories();
Map<Category, List<SubCategory>> categoryMap = new HashMap<Category, List<SubCategory>>();
for (Category category : categoriesList) {
List<SubCategory> subCategoryList = categoryConfigurationService
.getAllSubCategoriesByCategoryId(category.getId());
categoryMap.put(category, subCategoryList);
}
model.addAttribute("categoryMap", categoryMap);
model.addAttribute("featProd",
productConfigurationService.getFeaturedProducts());
return "home";
}
}
我有2个问题:
我如何可以存储在Spring对象
categoryMap
访问它在多页?我已经使用JSP和Servlets完成了相同的项目,并且我已将
categoryMap
存储在应用程序范围中,以便我可以在多个页面中使用它。这是一个正确的方法吗?如果不是,我怎么能以更好的方式做到这一点?
请帮忙!!由于
编辑:我想在我的应用程序的标题,显示该类别和子类别列表,这样我可以在所有页面使用这些(类似下图)
编辑:是除了编写代码以从每个控制器中的数据库中获取类别列表之外,还有其他方法可以遵循吗?
是的,这个列表对于所有用户都是一样的,但是我们真的可以将数据存储在单例作用域中吗?你能用一个代码示例来详细说明你的答案吗? – 2014-12-07 17:06:56
您会从您注入的类别中提供服务。现在该服务应该是一个在应用程序中共享的单例。这是你能做的最简单的事情。 '@Autowired private CategoryService categoryService; '并且在你的映射中,你将从服务获得映射:'model.addAttribute(“categoryMap”,categoryService.getYourMap());'不要把你的其他逻辑放到控制器中, – Vaelyr 2014-12-07 17:18:37
是的,你可以在你的服务中保留地图并使用它,但是因为多个线程将从每个控制器更新它,所以你需要使用同步来更新它的tread-safe – Panther 2014-12-07 17:21:50