版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42969074/article/details/85346195
前端页面的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;
}