業務需求:用戶登錄后展示用戶名、用戶對應的角色。EasyUI只不過是一個前端的框架,封裝了一些組件和樣式,你可以用jsp直接調后台獲取到用戶信息展示,但我這里想用html頁面,用目前流行的說法:前后端分離。效果跟你現在看到的頁面右上角差不多,當然功能不同,點擊名字不會跳頁,當鼠標放在名字可以展示當前用戶的角色:
實現很簡單,html通過easyUI的布局組件region:'north'指定頁面頂部展示:
<div class="wu-header" data-options="region:'north',border:false,split:true"> <div class="wu-header-left"> <h1>我的台管理系統</h1> </div> <div class="wu-header-right"> <p><strong id="userName">admin</strong>,歡迎您!|<a href="javascript:void(0)" onclick="logout()">退出</a></p> </div> </div>
在頁面加載時調用后台getLoginInfo接口獲取用戶信息的js:
// 獲取用戶信息並展示 $.ajax({ type: 'post', url: 'getLoginInfo', dataType: 'json', async: true, success: function (data) { if (data) { if (data.user) { roleValue = data.user.roleValue; var roleName; for (i = 0; i < roleStatus.length; i++) { if (roleStatus[i].id == roleValue) { roleName = roleStatus[i].value; break; } } $('#userName').html(data.user.userName); // 展示角色 $('#userName').tooltip({ position: 'right', content: '<span style="color:#fff">您的角色為:' + roleName + '</span>', onShow: function () { $(this).tooltip('tip').css({ backgroundColor: '#666', borderColor: '#666' }); } }); createMenu(roleValue); } else { window.location.href = "index.html"; } } } });
上面標黃的roleValue獲取角色的key值,用來在菜單加載時使用。而roleStatus就是一個下拉框選項值的數組,通過roleValue的id值去找到對應的value值。
后台Controller接口:
/** * 獲取登陸信息 * * @return */ @ResponseBody @RequestMapping(value = "/getLoginInfo", method = RequestMethod.POST) public Object getLoginInfo() { User user = null; Map<String, Object> resultMap = new HashMap<>(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest httpServletRequest = attributes.getRequest(); if (httpServletRequest != null && httpServletRequest.getSession(true) != null) { user = (User) httpServletRequest.getSession().getAttribute("user"); } if (user == null) { resultMap.put("errorMsg", "請先登錄."); } else { resultMap.put("user", user); } return resultMap; }
同理,點擊退出時調用登出接口,跳往登陸頁面。