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等
publicclassSysContext{ privatestaticThreadLocal<HttpServletRequest>requestLocal=newThreadLocal<HttpServletRequest>(); privatestaticThreadLocal<HttpServletResponse>responseLocal=newThreadLocal<HttpServletResponse>(); publicstaticHttpServletRequestgetRequest(){ returnrequestLocalget(); } publicstaticvoidsetRequest(HttpServletRequestrequest){ requestLocalset(request); } publicstaticHttpServletResponsegetResponse(){ returnresponseLocalget(); } publicstaticvoidsetResponse(HttpServletResponseresponse){ responseLocalset(response); } publicstaticHttpSessiongetSession(){ return(HttpSession)(getRequest())getSession(); } }
2.添加过滤器
publicclassGetContextFilterimplementsFilter{ @Override publicvoiddestroy(){ } @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse, FilterChainchain)throwsIOException,ServletException{ SysContextsetRequest((HttpServletRequest)request); SysContextsetResponse((HttpServletResponse)response); chaindoFilter(request,response); } @Override publicvoidinit(FilterConfigconfig)throwsServletException{ } }
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.springaopbefore
从session中取出用户名,如果不存在,抛出异常跳转,将错误信息放到request中
@Aspect publicclassAdminAspect{ ActionContextcontext=ActionContextgetContext(); HttpServletRequestrequest; HttpServletResponseresponse; @Before("execution(*comuneiActionAdminActiongetPrivileges())") publicvoidadminPrivilegeCheck() throwsThrowable{ HttpSessionsession=SysContextgetSession(); request=SysContextgetRequest(); response=SysContextgetResponse(); StringuserName=""; try{ userName=sessiongetAttribute("userName")toString(); if(userName==null||userNameequals("")) thrownewException("noprivilege"); }catch(Exceptionex){ requestsetAttribute("msg","{\"res\":\""+"无权限"+"\"}"); try{ requestgetRequestDispatcher("/jsp/jsonjsp")forward( request,response); }catch(ServletExceptione){ eprintStackTrace(); }catch(IOExceptione){ eprintStackTrace(); } } } }
5.applicationContext.xml
<beanid="adminAspect"class="comuneiaopAdminAspect"></bean>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。