Spring AOP in Java implements user permission verification
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='" // + url + "'</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
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. .
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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. ...

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...

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...

Start Spring using IntelliJIDEAUltimate version...

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...

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...

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

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...
