Reprinted source: https://blog.csdn.net/clementad/article/details/46807641
In the front-end browser, some data (such as the data in the data dictionary) can be taken and stored in the js object at the first request, so that you don't need to request the server every time you need it later. For pages that make heavy use of data dictionaries to populate drop-down boxes, this approach can greatly reduce server access. This approach works especially well with frames using iframes.
Specific implementation ideas and methods:
Create a cache.js file:
1. On the front-end page, define which data needs to be taken to the front-end cache at one time, and define an object to save the data:
- /**
- * Define the data dictionary category that needs to be obtained when the user logs in
- */
- var clsCodes = {"clsCodes" :
- ["BOOL",
- "STATUS",
- "USER_TYPE",
- "REPORT_STATUS"
- ]
- };
- /**
- * Get the data dictionary to the local
- */
- var dicts;
2. On the front-end page, define a function to call the back-end interface to obtain data, and then save it to the local cache object (dicts).
- function getDicts() {
- $.post(getContextPath() + "/api/sys/getDictList",
- clsCodes,
- function(resultBean, status, xhRequest) {
- if (resultBean.data != undefined) {
- dicts = resultBean.data;
- }
- },
- 'json');
- }
When the main page loads, call this method to get the data once and cache it. In this way, if the same data is needed in the future, it is obtained directly from the local object dicts.
Backend Controller:3. Define an interface to query the database (or query the server cache, as in the following example) to obtain data and return it to the front-end according to the request of the front-end:
- /**
- * Get multiple dictionary sets based on multiple classification numbers
- * @param clsCodes
- * @return {{"clsCode" : {"code1":"name1,"code2":"name2"...}}, ...}
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @ResponseBody
- @RequestMapping("getDictList")
- public ResultBean getDictList(@RequestParam(value = "clsCodes[]", required = true) String[] clsCodes) {
- ResultBean rb = new ResultBean();
- Map<String, Map<String, String>> dictCache = (Map<String, Map<String, String>>) CacheManager.getInstance().get(CacheConstants.DICT);
- Map dictMap = new LinkedHashMap<>(); //使用LinkedHashMap保证顺序
- if(dictCache != null){
- for(String clsCode: clsCodes){
- dictMap.put(clsCode, dictCache.get(clsCode));
- }
- }else{
- rb.setMessage( "Dictionary information is not available in the cache!" );
- rb.setSuccess(false);
- }
- rb.setData(dictMap);
- return rb;
- }