I had a one-page application when entering a URL in which it created a HashMap (used by my web page) that contained data from several databases. I followed these steps to load everything during server startup -
1- Created by ContextListenerClass
public class MyAppContextListener implements ServletContextListener @Autowired private MyDataProviderBean myDataProviderBean; public MyDataProviderBean getMyDataProviderBean() { return MyDataProviderBean; } public void setMyDataProviderBean( MyDataProviderBean MyDataProviderBean) { this.myDataProviderBean = MyDataProviderBean; } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("ServletContextListener destroyed"); } @Override public void contextInitialized(ServletContextEvent context) { System.out.println("ServletContextListener started"); ServletContext sc = context.getServletContext(); WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sc); MyDataProviderBean MyDataProviderBean = (MyDataProviderBean)springContext.getBean("myDataProviderBean"); Map<String, Object> myDataMap = MyDataProviderBean.getDataMap(); sc.setAttribute("myMap", myDataMap); }
2- Added entry below in web.xml
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>com.context.listener.MyAppContextListener</listener-class> </listener>
3- In my controller class, the code for the first card check in servletContext has been updated
@RequestMapping(value = "/index", method = RequestMethod.GET) public String index(@ModelAttribute("model") ModelMap model) { Map<String, Object> myDataMap = new HashMap<String, Object>(); if (context != null && context.getAttribute("myMap")!=null) { myDataMap=(Map<String, Object>)context.getAttribute("myMap"); } else { myDataMap = myDataProviderBean.getDataMap(); } for (String key : myDataMap.keySet()) { model.addAttribute(key, myDataMap.get(key)); } return "myWebPage"; }
With this big change, when I start my tomcat, it loads the dataMap during startTime and puts everything in the servletContext, which is then used by the Controller class to get the results from the already filled servletContext.
Amit Singh Apr 20 '16 at 11:03 2016-04-20 11:03
source share