spring aop intercepts the business method and implements the permission control example

  • 2020-05-30 20:07:41
  • OfStack

Difficult points: aop class is a common java class, and session cannot be injected. Then how to get user information in a stateful system? session is the only way, so it becomes very important to get session. After thinking about it for a long time, I found the solution on the Internet.

Idea is:

i. SysContext member variables request,session,response

The purpose of ii. Filter is to assign values to members of SysContext

iii. Then use this SysContext value in AOP

To use it well, you need to understand the order in which ThreadLocal and Filter execute

1.aop gets request, response, session, etc

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){ 
  public static HttpServletResponse getResponse(){ 
   return responseLocalget(); 
  public static void setResponse(HttpServletResponse response){ 
  public static HttpSession getSession(){ 
   return (HttpSession)(getRequest())getSession(); 

2. Add a filter

public class GetContextFilter implements Filter{ 
  public void destroy() { 
  public void doFilter(ServletRequest request, ServletResponse response, 
    FilterChain chain) throws IOException, ServletException { 
   chaindoFilter(request, response); 
  public void init(FilterConfig config) throws ServletException { 

3. Configure web. xml

This section is placed first so that all requests can be filtered


4.spring aop before

Take the user name from session, if it doesn't exist, throw an exception jump, and put the error message into request

 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(); 
     throw new Exception("no privilege"); 
   } catch (Exception ex) { 
    requestsetAttribute("msg", "{\"res\":\"" + " Without permission " + "\"}"); 
    try { 
       request, response); 
    } catch (ServletException e) { 
    } catch (IOException e) { 


<bean id="adminAspect" class="comuneiaopAdminAspect"></bean> 

Related articles: