Home Java javaTutorial Spring AOP in Java implements user permission verification

Spring AOP in Java implements user permission verification

Feb 03, 2017 pm 01:19 PM

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;
}
Copy after login

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;
 
}
Copy after login

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;
  } 
}
Copy after login

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>
Copy after login

Just configure the 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles