I have created a spring mvc web application. My menus are database i.e they are stored in the databases. Whenever I call index.jsp which is my home page from a different browser, the menu items are retrieved every time from database. How can I stored the menu items in a global variable which can be accessed anytime without hitting the database again or until I restart the server.
解决方案
You requirement can be sufficed in 2 ways:
Server cache:
Use some open source server cache library like ehcache which lets you store data (you app data or data retrieved from database or data received from some 3rd party app call) in server memory. Idea is that instead of performing same 3rd party call which is expected to give same result, do it once and then store it in server cache.
Ehcache works well with Spring framework, and in fact we use ehcache for server side caching for our enterprise application which is based on Spring framework.
Browser database storage:
HTML5 provide IndexedDB API which lets you store data in browser database.
So, you can retrieve the data from server once and then store it in local database, then whenever you need data you can first check if it is present in local database or not, if not then retrieve and store in local db, else fetch from local db.
Advantage of this approach is that you can save even the server call, so lesser network traffic.
Depending on you requirement, you can choose one option.
I would NOT recommend storing data, which is retrieved from database, in global variables. It is really not a scalable approach.
You can find plenty of online tutorials, but 1 would suggest in each case: