spring aop 阻攔業務辦法,完成權限控制示例。本站提示廣大學習愛好者:(spring aop 阻攔業務辦法,完成權限控制示例)文章只能為提供參考,不一定能成為您想要的結果。以下是spring aop 阻攔業務辦法,完成權限控制示例正文
難點:aop類是普通的java類,session是無法注入的,那麼在有形態的零碎中如何獲取用戶相關信息呢,session是必經之路啊,獲取session就變的很重要。思索很久沒有方法,後來在網上看到理解決方法。
思緒是:
i. SysContext 成員變量 request,session,response
ii. Filter 目的是給 SysContext 中的成員賦值
iii.然後在AOP中運用這個SysContext的值
要用好,需求了解 ThreadLocal和 和Filter 執行順序
1.aop獲取request,response,session等
public class SysContext { private static ThreadLocal<HttpServletRequest> requestLocal=new ThreadLocal<HttpServletRequest>(); private static ThreadLocal<HttpServletResponse> responseLocal=new ThreadLocal<HttpServletResponse>(); public static HttpServletRequest getRequest(){ return requestLocalget(); } public static void setRequest(HttpServletRequest request){ requestLocalset(request); } public static HttpServletResponse getResponse(){ return responseLocalget(); } public static void setResponse(HttpServletResponse response){ responseLocalset(response); } public static HttpSession getSession(){ return (HttpSession)(getRequest())getSession(); } }
2.添加過濾器
public class GetContextFilter implements Filter{ @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { SysContextsetRequest((HttpServletRequest)request); SysContextsetResponse((HttpServletResponse)response); chaindoFilter(request, response); } @Override public void init(FilterConfig config) throws ServletException { } }
3.配置web.xml
將這局部放置在最後面,這樣可以過濾到一切的懇求
<filter> <filter-name>sessionFilter</filter-name> <filter-class>comuneifilterGetContextFilter</filter-class> </filter> <filter-mapping> <filter-name>sessionFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping>
4.spring aop before
從session中取出用戶名,假如不存在,拋出異常跳轉,將錯誤信息放到request中
@Aspect public class AdminAspect { ActionContext context = ActionContextgetContext(); HttpServletRequest request; HttpServletResponse response; @Before("execution(* comuneiActionAdminActiongetPrivileges())") public void adminPrivilegeCheck() throws Throwable { HttpSession session = SysContextgetSession(); request = SysContextgetRequest(); response = SysContextgetResponse(); String userName = ""; try { userName = sessiongetAttribute("userName")toString(); if(userName==null||userNameequals("")) throw new Exception("no privilege"); } catch (Exception ex) { requestsetAttribute("msg", "{\"res\":\"" + "無權限" + "\"}"); try { requestgetRequestDispatcher("/jsp/jsonjsp")forward( request, response); } catch (ServletException e) { eprintStackTrace(); } catch (IOException e) { eprintStackTrace(); } } } }
5.applicationContext.xml
<bean id="adminAspect" class="comuneiaopAdminAspect"></bean>
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。