Java responsibility chain model and project application, and java liability Project Application

Source: Internet
Author: User

Java responsibility chain model and project application, and java liability Project Application
1. Preface

The last time we learned about the design of the java responsibility chain model, we will show you the practical application of the responsibility chain model project. How to quickly build a project with the responsibility chain model.

 

2. Simple technical preparation

We need to use the combined use of such knowledge in the project to better interpret it.

Required skills:
Definition of simple annotations;
Use of Spring interceptor;
Brief answer: the definition of the responsibility chain model;

With previous knowledge points, we can quickly establish a responsibility chain for security verification.

3. Scenario Simulation

Scenario: in the system, we need some security verification structures, such as login verification and role verification. Next we will use the responsibility chain model to develop this process-based verification.
 

4. Design Mode

We will design a web project using springmvc framework. The development language uses JAVA.
Execution Process:

SpringMVC interceptor ---> intercepts specified annotations ---> enters the responsibility chain for processing
 

5 encoding practices 5.1 annotation Definition

Define a Permission Annotation

/**
* Permission Interception
*@ AuthorMR. YongGan. Zhang
*
*/
@ Inherited
@ Brief ented
@ Retention (RetentionPolicy.RUNTIME)
@ Target (ElementType.METHOD)
Public @ InterfacePermission {

VerifyType verifyType ()DefaultVerifyType.LOGIN;

String [] verifyValue ()Default"";

}
 

 
Here is the validation type of Enumeration type
 

/**
* Type of verification
*
* NONE is not verified.
* LOGIN Verification
* ROLE Verification
*
*@ AuthorMR. YongGan. Zhang
*
*/
Public EnumVerifyType {
 
NONE,LOGIN,ROLE;

}
 

 

5.2 interceptor Definition

We define the interceptor PermissionInterceptor, which is actually an annotation parser. SpringMVC is used as the interceptor.
 
We can use the springMVC Interceptor to implement three methods of the org. springframework. web. servlet. HandlerInterceptor rewrite interface.
Let's take a look at how it is implemented.
 

ImportJava. lang. reflect. Method;
 
ImportJavax. servlet. http. HttpServletRequest;
ImportJavax. servlet. http. HttpServletResponse;
 
ImportOrg. springframework. web. method. HandlerMethod;
ImportOrg. springframework. web. servlet. HandlerInterceptor;
ImportOrg. springframework. web. servlet. ModelAndView;
 
ImportCom. shsxt. framework. Permission. Permission;
ImportCom. shsxt. framework. Permission. handlerchain. PermissionHandlerChainStaticFactory;
ImportCom. shsxt. framework. Permission. handlerchain. PermissionWithNone;
ImportCom. shsxt. framework. constant. VerifyType;
/**
* Security Verification
*
* 1. Intercept User Login
* 2. Permission Interception
*
*
*@ AuthorMR. YongGan. Zhang
*@ Version1.0.1
*
* Remarks: 1.0.0 Implements user login interception. 1.0.1 adds implementation permissions.
*
*/
 
Public ClassPermissionInterceptorImplementsHandlerInterceptor {

@ Override
Public BooleanPreHandle (HttpServletRequest request, HttpServletResponse response, Object handler)
ThrowsException {

System.Err. Println ("Enter PermissionInterceptor... ");
System.Err. Println (handler. getClass (). getName ());

If(HandlerInstanceofHandlerMethod ){
 
HandlerMethod hm = (HandlerMethod) handler;
 
Method method = hm. getMethod ();

// If the Permission annotation is included
If(Method. isAnnotationPresent (Permission.Class)){//
 
Permission permission = method. getAnnotation (Permission.Class);
// Obtain the attributes in the Annotation
VerifyType verifyType = permission. verifyType ();

// Obtain the permission verification Value
String [] verifyValue = permission. verifyValue ();

// Check the responsibility chain mode
PermissionWithNone permissionWithNone = PermissionHandlerChainStaticFactory.CreatePermissionWithNone();
// Execution result
BooleanBool = permissionWithNone. handleChain (verifyType, request, verifyValue );
System.Err. Println (bool );
ReturnBool;
}
}
Return True;
}
 
@ Override
Public VoidPostHandle (HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView)ThrowsException {

}
 
@ Override
Public VoidAfterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
ThrowsException {

}
 
}

 
We have defined the Interceptor. Next we need to configure our interceptor to manage it in the springMVC container.



Configure the defined interceptor on the servlet-context.xml.
 

<Mvc: interceptors>
<Mvc: interceptor>
<Mvc: mapping path ="/**"/>
<Mvc: exclude-mapping path ="/User/userLogin"/>
<Mvc: exclude-mapping path ="/Index"/>
<Mvc: exclude-mapping path ="/Css /**"/>
<Mvc: exclude-mapping path ="/Images /**"/>
<Mvc: exclude-mapping path ="/Jquery-easyui-1.3.3 /**"/>
<Mvc: exclude-mapping path ="/Js /**"/>
<Mvc: exclude-mapping path ="/ZTree_v3 /**"/>
<Bean class ="Com. shsxt. framework. interceptor. PermissionInterceptor"/>
</Mvc: interceptor>
</Mvc: interceptors>

 
In this way, we configure the Interceptor to the springMVC container.

5.3 responsibility chain design

5.3.1 abstract responsibility chain

Permissiontransferacthandlerchain: defines the handling rules of the responsible chain.
 

/**
* Permission control responsibility chain
*@ AuthorMR. YongGan. Zhang
*
*/
Public Abstract ClassPermissionpolicacthandlerchain {

// Control chain
ProtectedPermissionpolicacthandlerchain successor;

Public Abstract BooleanHandleChain (VerifyType verifyType, HttpServletRequest request, String [] verifyValue );

PublicPermissiontransferacthandlerchain getHandlerChain (){
Return This. Successor;
}


Public VoidSetSuccessor (permissionpolicacthandlerchain successor ){

This. Successor = successor;

}

}

 

5.3.2 specific business processing objects

PermissionWithNone PermissionWithLogin PermissionWithRole must inherit the abstract processing chain.
 

5.3.2.1. PermissionWithNone is not verified
/**
*
*@ AuthorMR. YongGan. Zhang
*
*/
Public ClassPermissionWithNoneExtendsPermissionpolicacthandlerchain {
 
@ Override
Public BooleanHandleChain (VerifyType verifyType, HttpServletRequest request, String [] verifyValue ){
 
If(VerifyType = VerifyType.NONE){
Return True;
}Else{
SetSuccessor (PermissionHandlerChainStaticFactory.CreatePermissionWithLogin());
ReturnGetHandlerChain (). handleChain (verifyType, request, verifyValue );
}
}
 
}
 
5.3.2.2. PermissionWithLogin login verification
/**
*
*@ AuthorMR. YongGan. Zhang
*
*/
Public ClassPermissionWithLoginExtendsPermissionpolicacthandlerchain {
 
@ Override
Public BooleanHandleChain (VerifyType verifyType, HttpServletRequest request, String [] verifyValue ){

If(VerifyType = VerifyType.LOGIN){
/**
* Implement login interception Verification
*/
BooleanStatus = VerificationLoginUtil.IsLoginedStatus(Request );
ReturnStatus;
}Else{
SetSuccessor (PermissionHandlerChainStaticFactory.CreatePermissionWithRole());
ReturnGetHandlerChain (). handleChain (verifyType, request, verifyValue );
}
}
}
 
 

RemarksBooleanStatus = VerificationLoginUtil.IsLoginedStatus(Request );
The login verification here must be done according to the actual business.

5.3.2.3.PermissionWithRole permission Verification
/**
*@ AuthorMR. YongGan. Zhang
*/
Public ClassPermissionWithRoleExtendsPermissionpolicacthandlerchain {
 
@ Override
Public BooleanHandleChain (VerifyType verifyType, HttpServletRequest request, String [] verifyValue ){
// Role verification for login
If(VerifyType = VerifyType.ROLE){
BooleanStatus = VerificationLoginUtil.IsLoginedStatus(Request );
System.Out. Println (status );
If(! Status ){
Return False;
}
 
/**
* Implement login interception Verification
*/
List <String> verify = Arrays.AsList(VerifyValue );
 
// User-contained permissions [designed based on actual business]
List <String> userPermission = (List <String>) request. getSession ()
. GetAttribute (CrmConstant.USER_PERMISSIONS);
If(Verify! =Null& Verify. size ()> 0 ){
For(String cherck: verify ){
BooleanFlag = userPermission. contains (cherck); // checks whether the permission contains
If(! Flag ){
ReturnFlag; // false if not included
}
}
}
Return True;
 
}Else{
Throw NewYgException ("PS001", "security verification failed to recognize ");
}
}
}

 

5.3.3 static factory design of processing chain
/**
* Static factory mode of the responsibility chain object
*@ AuthorMR. YongGan. Zhang
*/
Public ClassPermissionHandlerChainStaticFactory {

Public StaticPermissionWithNone createPermissionWithNone (){
Return NewPermissionWithNone ();
}

Public StaticPermissionWithLogin createPermissionWithLogin (){
Return NewPermissionWithLogin ();
}

Public StaticPermissionWithRole createPermissionWithRole (){
Return NewPermissionWithRole ();
}
}

 

5.4 how to use



Add annotations when the structure we designed requires security verification.
@ Permission (verifyType = VerifyType. ROLE, verifyValue = {"101011 "})
Indicates that the value to be verified for role verification is 101011.
 
This is what we need to learn during design. Annotations are used to decouple our business code. in the use of the responsibility chain model, we are more horizontally scalable. As the business develops, we can add blacklists or daytime verification, and add a connection to the risk control system.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.