1. 程式人生 > >將後臺資料存放入Application域中

將後臺資料存放入Application域中

前端頁面的head、menu、foot … 的資料,這些資料並不會經常更新,而資料是存放在資料庫中,如果每次重新整理都去訪問資料庫,則會給資料庫帶來壓力,所以將這些資料放入Application中,程式碼如下:

/**
 * 初始化元件
 */
@Component("initComponent")
public class InitComponent implements ServletContextListener,ApplicationContextAware{

	private static ApplicationContext applicationContext;
	
	public
void refreshSystem(ServletContext application) ArcTypeService arcTypeService=(ArcTypeService) applicationContext.getBean("arcTypeService"); List<ArcType> arcTypeList=arcTypeService.list(null); // 查詢所有帖子型別 application.setAttribute("arcTypeList", arcTypeList); LinkService linkService=
(LinkService) applicationContext.getBean("linkService"); // 查詢所有友情連結 List<Link> linkList=linkService.list(null); application.setAttribute("linkList", linkList); ArticleService articleService=(ArticleService) applicationContext.getBean("articleService"); List<Article> newestArticleList=
articleService.getNewest(); // 獲取最新7條帖子 application.setAttribute("newestArticleList", newestArticleList); List<Article> recommendArticleList=articleService.getRecommend(); // 獲取最新7條推薦的帖子 application.setAttribute("recommendArticleList", recommendArticleList); List<Article> slideArticleList=articleService.getSlide(); // 獲取最新5條幻燈帖子 application.setAttribute("slideArticleList", slideArticleList); } public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext application=servletContextEvent.getServletContext(); refreshSystem(application); } public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext=applicationContext; }

然後就可以在前臺頁面拿到相應的資料了。
如果要重新整理一下Application中的資料(一般在新增、修改、刪除的Controller寫入)程式碼如下:
要在對應的Controller中加Bean。

    @Autowired
	private InitComponent initComponent;

這裡用一個刪除做為例子:

/**
	 * 刪除友情連結資訊
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String delete(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		String []idsStr=ids.split(",");
		JSONObject result=new JSONObject();
		for(int i=0;i<idsStr.length;i++){
			linkService.delete(Integer.parseInt(idsStr[i]));				
		}
		// 刷新系統快取
	    initComponent.refreshSystem(ContextLoader.getCurrentWebApplicationContext().getServletContext()); 
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}