Home >Java >javaTutorial >Spring AOP in Java implements user permission verification

Spring AOP in Java implements user permission verification

高洛峰
高洛峰Original
2017-02-03 13:19:221766browse

Every project will have a permission management system

Whether you are a simple enterprise website or an extremely complex platform-level project, it will involve the essential business of user login and permission management. logic. Some people say, what permissions do enterprise websites need to manage? Okay, your page may be called a static page. Even so, you will definitely have background management and login functions.

Every project will have these almost identical business logics. Can we make them into a universal system?

AOP implements user authority verification

The scenarios used by AOP in actual projects mainly include authority management (Authority Management), transaction management (Transaction Management), security management (Security), and log management ( Logging) and debugging management (Debugging), etc.

So, we can use AOP to implement permission verification directly. How to manage permissions in your project and what the level of management granularity is depends entirely on the needs of the project and will not be discussed here at all.

Let’s talk about the idea first: use custom annotations and interceptors to perform some permission authentication when you need it. What is still involved here is enum (enumeration), annotation (custom annotation) and interceptor related knowledge. Without further ado, let’s just start writing the code.

Start playing with the code

**1. Create the AuthorityType.java enumeration class

public enum AuthorityType {
 
  // 登录和权限都验证 默认
  Validate,
 
  // 不验证
  NoValidate,
 
  // 不验证权限
  NoAuthority;
}

The role of this enumeration class is still to make custom annotations fun to use Still want it.

2. Create a new Authority.java custom annotation class

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Authority {
  // 默认验证
  AuthorityType value() default AuthorityType.Validate;
 
}

3. Create another AuthorityAnnotationInterceptor.java class

/**
 * 权限认证拦截器
 *
 */
public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
 
  if (handler instanceof HandlerMethod) {
    HandlerMethod hm = (HandlerMethod) handler;
 
    Class<?> clazz = hm.getBeanType();
    Method m = hm.getMethod();
    try {
      if (clazz != null && m != null) {
        boolean isClzAnnotation = clazz.isAnnotationPresent(Authority.class);
        boolean isMethondAnnotation = m.isAnnotationPresent(Authority.class);
        Authority authority = null;
        // 如果方法和类声明中同时存在这个注解,那么方法中的会覆盖类中的设定。
        if (isMethondAnnotation) {
          authority = m.getAnnotation(Authority.class);
        } else if (isClzAnnotation) {
          authority = clazz.getAnnotation(Authority.class);
        }
        int code = -1;
        String msg = "";
        if (authority != null) {
          if (AuthorityType.NoValidate == authority.value()) {
            // 标记为不验证,放行
            return true;
          } else if (AuthorityType.NoAuthority == authority.value()) {
            // 不验证权限,验证是否登录
            // TODO:
            return true;
          } else {
            // 验证登录及权限
            // TODO:
 
            code = 1;
            msg = "验证成功!";
            return true;
          }
        }
 
        // //跳转
        // String url = "";
        // response.getWriter().write("<script>top.location.href=&#39;"
        // + url + "&#39;</script>");
        // return false;
 
        // 未通过验证,返回提示json
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("code", code);
        responseMap.put("msg", msg);
        responseMap.put("params", "");
        responseMap.put("rows", "");
        String json = new Gson().toJson(responseMap);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(json);
        return false;
      }
    } catch (Exception e) {
    }
  }
  return false;
  } 
}

The purpose of this class is to perform authority authentication on methods and classes marked with the Authority tag. I have divided it into three types: full verification, login verification only, and no verification to meet our business needs.

The return value here can be a JSON string, or it can jump to the corresponding page to achieve the effect you want.

4. Configure the interceptor

<mvc:interceptors>
  <!-- 权限认证拦截器 -->
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="cn.mayongfa.interceptor.AuthorityAnnotationInterceptor"></bean>
  </mvc:interceptor>
</mvc:interceptors>

Just configure the ad6669fcacaee0dbae1311edd5eb66da node under the /WebContent/WEB-INF/springMVC-servlet.xml file. Here you can configure the specific URLs to be intercepted.

The permission verification has been completed here. How to use it?

It’s very simple to use

Because of our interceptor configuration, the default for our custom annotations is verification, so we only need to label the class name and method name. .

Java之Spring AOP 实现用户权限验证

Of course, you can set the default in the interceptor to verify all requests, and then set the request to not verify.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to Java's Spring AOP implementing user permission verification, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn