Java responsibility chain model and practical application of the project

Source: Internet
Author: User

1. Preface

The last time we met 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 chain of responsibility for the project to use.

2. Simple Technical Preparation

We need to use such a combination of knowledge in the project to better interpret.

Required Skills:
Definition of simple annotations;
Use of spring interceptors;
The definition of the responsibility chain mode of Jane's answer;

With the knowledge of the previous preparation, we can quickly set up a chain of responsibilities to do security checks.

3. Scene Simulation

Scenario: In the system we need some security check structure, such as login check and role check. Next we use the chain of responsibility model to develop this process validation.

4. Design mode

We will design a Web project that uses the SPRINGMVC framework. The development language uses Java.
Execute the Process execution process:

SPRINGMVC Interceptors---> Intercept designated Annotations---> enter the liability chain processing

5 Coding Combat 5.1 Annotation Definitions

Define a permission annotation

/**
* Permission interception
* @author MR. Yonggan.zhang
*
*/
@Inherited
@Documented
@Retention (Retentionpolicy. RUNTIME)
@Target (ElementType. METHOD)
Public @interface Permission {

Verifytype verifytype () default verifytype. LOGIN;

String[] Verifyvalue () default "";

}


Where is the checksum type of the enumeration type

/**
* Type of calibration
*
* None not verified
* Login Login Check
* Role Roles Check
*
* @author MR. Yonggan.zhang
*
*/
Public enum Verifytype {

NONE, LOGIN, ROLE;

}

5.2 Interceptor Definition

We define the Interceptor permissioninterceptor, which is actually an annotation parser. We will use the SPRINGMVC to make interceptors.

We can implement the three methods of Org.springframework.web.servlet.HandlerInterceptor rewrite interface using SPRINGMVC interceptor.
Let's see how it's achieved.

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;
/**
* Safety Check
*
* 1. Intercept whether the user is logged in
* 2. Permission interception
*
*
*@authorMR. Yonggan.zhang
*@version1.0.1
*
* Note: 1.0.0 implementation of user login interception 1.0.1 increased implementation rights
*
*/

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 Permission annotations are included
if(Method.isannotationpresent (Permission.class)) { //

Permission Permission = method.getannotation (Permission.class);
Get Properties in annotations
Verifytype Verifytype = Permission.verifytype ();

Get permission Check value
string[] Verifyvalue = Permission.verifyvalue ();

Responsibility Chain Mode Check
Permissionwithnone Permissionwithnone = permissionhandlerchainstaticfactory.Createpermissionwithnone();
Execution results
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've defined the interceptor, and the next step is to configure our interceptor to be managed in our SPRINGMVC container.



Configure a well-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>


This allows us to configure the interceptor to the SPRINGMVC container.

5.3 Design of the liability chain

5.3.1 Abstract Responsibility Chain

Permissionabstracthandlerchain: Define responsibility chain processing rules.

/**
* Authority control responsibility Chain
*@authorMR. Yonggan.zhang
*
*/
Public Abstract classPermissionabstracthandlerchain {

Control chain
protectedPermissionabstracthandlerchain successor;

Public Abstract BooleanHandlechain (Verifytype verifytype, httpservletrequest request, string[] verifyvalue);

PublicPermissionabstracthandlerchain Gethandlerchain () {
return This. successor;
}


Public voidSetsuccessor (Permissionabstracthandlerchain successor) {

This. successor = successor;

}

}

5.3.2 Specific Business Processing objects

Permissionwithnone Permissionwithlogin Permissionwithrole All need to inherit the abstract processing chain.

5.3.2.1. Permissionwithnone do not check
/**
*
*@authorMR. Yonggan.zhang
*
*/
Public classPermissionwithnoneextendsPermissionabstracthandlerchain {

@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 Check
/**
*
*@authorMR. Yonggan.zhang
*
*/
Public classPermissionwithloginextendsPermissionabstracthandlerchain {

@Override
Public BooleanHandlechain (Verifytype verifytype, HttpServletRequest request,string[] verifyvalue) {

if(Verifytype = = Verifytype.LOGIN) {
/**
* Implement login Intercept check
*/
BooleanStatus = Verificationloginutil.Isloginedstatus(request);
returnStatus
}Else{
Setsuccessor (permissionhandlerchainstaticfactory.Createpermissionwithrole());
returnGethandlerchain (). Handlechain (Verifytype, request, verifyvalue);
}
}
}

Notes boolean status = Verificationloginutil. Isloginedstatus (request);
The login verification here needs to be done with the actual business.

5.3.2.3. Permissionwithrole Permissions Check
/**
*@authorMR. Yonggan.zhang
*/
Public classPermissionwithroleextendsPermissionabstracthandlerchain {

@Override
Public BooleanHandlechain (Verifytype verifytype, httpservletrequest request, string[] verifyvalue) {
Role Verification Implementation Login
if(Verifytype = = Verifytype.ROLE) {
BooleanStatus = Verificationloginutil.Isloginedstatus(request);
System. out. println (status);
if(!status) {
return false;
}

/**
* Implement login Intercept check
*/
list<string> Verify = Arrays.aslist(Verifyvalue);

User-included permissions "design with 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);//Detect whether the permission contains
if(!flag) {
returnflag;//is not included returns false
}
}
}
return true;

}Else{
Throw NewYgexception ("PS001", "Security check not recognized");
}
}
}

Static plant design of 5.3.3 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 we design a structure that requires a safety check
@Permission (Verifytype = verifytype.role, Verifyvalue = {"101011"})
Indicates that the role check requires a checksum value of 101011

This is where we need to learn when we design. Using annotations to decouple us from the business code, the use of the responsibility chain model more horizontal expansion, later with the development of the business, you can add blacklist or daytime check, and add the connection of the wind control system.

Java responsibility chain model and practical application of the project

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.