ssm系統攔截許可權
阿新 • • 發佈:2021-11-06
1.系統許可權的攔截
對於一個系統來說,系統當中的不同使用者訪問資源的許可權也是不同的
對於系統來說,使用者,角色,許可權必不可少,通常都是通過5張表來實現系統的許可權控制
使用者表,使用者角色關係表,角色表,角色許可權關係表,許可權表(選單表)
- 不同的使用者登陸,進來之後,看到的導航是一樣的嗎?
- 使用者登陸成功後,根據使用者id查詢他的許可權列表,動態的展示導航
- 怎麼保證不同的使用者,不能操作不屬於他的許可權?
- 全域性的攔截器攔截每次請求,先判斷請求資源地址是否是公開資源,如果不是,
- 判斷使用者是否登陸,假如登陸,通過使用者id查詢到使用者的許可權列表list,
- 拿著使用者請求的資源地址和list進行對比,如果包含在其中,放行;
2.程式碼實現
- 自定義許可權攔截器
package com.oracle.shop.security; import com.oracle.shop.po.Menu; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.List; /** *@Description: 許可權攔截器 */ public class PremisstionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //在請求處理之前判斷使用者請求的地址是否合法,如果不合法就執行響應的操作 //獲取請求路徑 String path = request.getRequestURI(); if (path.contains("/common")){ //請求公共資源 return true; }else { //訪問非靜態資源 判斷使用者是否登陸 HttpSession session = request.getSession(false); if (null==session){//一定沒有登陸 response.sendRedirect(request.getContextPath()+"/common/toLogin"); return false; }else { if (null==session.getAttribute("user")){ //使用者沒有登陸過 response.sendRedirect(request.getContextPath()+"/common/toLogin"); return false; }else{ //使用者登陸了,判斷請求是否合法 //獲取使用者許可權下,可以訪問的頁面列表 if (path.contains("/index")){ return true; }else { List<Menu> menuList = (List<Menu>)session.getAttribute("menuList"); //遍歷檢視請求是否合法 boolean check = false; for (Menu menu:menuList){ if (path.contains(menu.getMenuKey())){ check = true; break; } } if (check){ return true; }else { response.sendRedirect(request.getContextPath()+"/common/noauth"); return false; } } } } } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
- 在springmvc.xml當中配置攔截器
<mvc:interceptors> <mvc:interceptor> <!--攔截的路徑所有--> <mvc:mapping path="/**"/> <!--不攔共同資源--> <mvc:exclude-mapping path="/common"/> <bean class="com.oracle.shop.security.PremisstionInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>