A method of SPRING-MVC permission control based on annotation

Source: Internet
Author: User

Brief introduction

This paper introduces a method of using annotation to control the rights of SPRING-MVC. Define permission entries by enumerating classes. Label the annotation on the Spring-mvc method that requires permission to control it. Then, define the global filter in SPRING-MVC, filter all the SPRING-MVC methods, and view the permissions annotation information on the method to control the permissions.
Program Source code: https://github.com/eagle0445/sample/

Advantages

It is easier to write annotation annotations on methods that require control of permissions, and the IDE can identify support for annotation. It is convenient to view the permissions configuration because annotation is on the method and does not have to look elsewhere. The implementation method is relatively simple.

Implementation 1. Create a Permission enumeration class

Establishes a permission enumeration type that describes the kind of permission that contains the name of the permission. Each enumeration value contains the Chinese name of the permission and the permission index value (that is, the permission bit). (think: Whether you can directly use the Chinese name as the name of the enumeration value, I have already used the Chinese enumeration name in other programs, no problem at the moment)

<!--Lang:java--PublicEnum authoritytype{Contains the Chinese name of the enumeration, the index value of the enumeration worker ("Adding and deleting staff",1), Sales_order_create ("Create Order",6), Sales_order_find ("View Orders",7), Sales_order_modify ("Modify Order",8), Sales_order_delete ("Delete Order",9),;private String name;Privateint index;Private Authoritytype(String name,IntIndex{THIS.name = name;This.index = index;}PublicStringGetName(){return name;Public void SetName(String name){THIS.name = name;}Public Int GetIndex ()  {return Index;} public  void  setIndex  (int< Span class= "Hljs-params" > index)  {this.index = Index;}}   
2. Enumeration class for Login methods

Enumeration class for Login mode, page for traditional login page, JSON for AJAX login

<!-- lang: java -->public enum ResultTypeEnum {//整页刷新page, //json数据json}
3. Establish the annotation class that represents the permission

Establish the annotation class for labeling where permission validation is required

<!--Lang:Java-ImportJava. lang. annotation. documented;ImportJava. lang. annotation. ElementType;ImportJava. lang. annotation. Retention;ImportJava. lang. Annotation. Retentionpolicy; import java. lang. Annotation. target;@Target (ElementType.  METHOD) @Retention (retentionpolicy.runtime) @Documentedpublic @interface fireauthority { authoritytype[] authoritytypes (); resulttypeenum resulttype () default resulttypeenum. Page;}      
4. Add a permission field to the user class

Add a text field to the user class to indicate permissions, the field length is 250 characters (because MySQL default 255 characters, can represent 250 permissions should suffice), the character content is 0 or 1. 1 indicates a permission, and 0 means no permission. Tip: For the user's permission configuration, simply set the corresponding permission bit to 0 or 1.

<!-- lang: sql -->    create table user (        id integer not null auto_increment,        name varchar(255),        right_content varchar(255),        primary key (id)    ) type=InnoDB
5. Permission Validation algorithm

The method of authority judgment, the realization algorithm of authority judgment, is used to determine whether there is permission

<!--Lang:java--PublicClass Authorityhelper{/** * Determine if you have permission *@paramAkey the index value of the position in the astring, which is the permission bit *@paramastring permission fields, such as 11010101011101 *@return*/Public Static Boolean Hasauthority(int akey,string astring) { return constanhelper.getauthorityvaule (AKEY,RC); if (astring==null | | " ". Equals (astring)) { return false;} char value = Astring.charat (Akey); if (value = = ' 1 ') { return true;} return false;}}               
6. Interceptor class for establishing control permissions

Establish the Interceptor class for filtering methods that require control of permissions.

<!--Lang:java--ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.URLEncoder;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJavax.servlet.http.HttpSession;ImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;ImportOrg.springframework.web.method.HandlerMethod;ImportOrg.springframework.web.servlet.handler.HandlerInterceptorAdapter;PublicClass Authorityannotationinterceptor Extends Handlerinterceptoradapter{Final Logger Logger = Loggerfactory.getlogger (GetClass ()); @Overridepublic boolean prehandle (HttpServletRequest request, httpservletresponse response, Object handler) throws Exception {log Ger.debug (""); Handlermethod handler2= (Handlermethod) handler; Fireauthority fireauthority = handler2.getmethodannotation (Fireauthority.class);IfNULL = = fireauthority) {No claims permission, releaseReturnTrue } logger.debug ("Fireauthority", fireauthority.tostring ()); HttpSession session = Request.getsession (); Worker manager = (worker) Session.getattribute (Sessionhelper.workerhandler); Boolean Aflag =FalseFor (Authoritytype at:fireAuthority.authorityTypes ()) {if (Authorityhelper.hasauthority (At.getindex (), manager.getrightcontent ()) = =True) {Aflag =TrueBreak } }Iffalse = = Aflag) {if (fireauthority.resulttype () = = Resulttypeenum.page) {Traditional login page StringBuilder sb =New StringBuilder (); Sb.append (Request.getcontextpath ()); Sb.append ("/oprst.jsp?oprst=false&opmsg="). Append (Urlencoder.encode (controllerproperty.not_have_authority,"Utf-8")); Response.sendredirect (Sb.tostring ()); }Else if (fireauthority.resulttype () = = Resulttypeenum.json) { //ajax type of login prompt response.setcharacterencoding ("utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); OutputStream out = Response.getoutputstream (); PrintWriter pw = new PrintWriter (new OutputStreamWriter (out,"Utf-8")); Pw.println ("{\" result\ ": false , \ "code\": 12,\ "errormessage\": \ "" +controllerproperty.not_have_authority+"\"} "); Pw.flush (); Pw.close (); } return false;} return true;}}             
7. Configuring the Interceptor Class

Configure the Interceptor in SPRING-MVC to implement filtering.

<!--Lang:xml--<mvc:interceptors>  <bean class = "Interceptor . Authorityannotationinterceptor "></< Span class= "Hljs-name" >bean> </ mvc:interceptors>         
8. Labeling methods that require control of permissions

Add a corresponding callout to the Spring-mvc method that requires control access.
Way One

<!-- lang: java -->@FireAuthority(AuthorityType. SALES_ORDER_CREATE)@RequestMapping(value="/save.spr", method=RequestMethod.POST)public ModelAndView save(String name) throws Exception { //some code}

Way Two

<!-- lang: java -->@FireAuthority(authorityTypes = {AuthorityType.SALES_ORDER_DELETE,AuthorityType.SALES_ORDER_CREATE}) @RequestMapping(value="/save.spr", method=RequestMethod.POST) public ModelAndView save(String name) throws Exception { //some code }

Mode three

    <!-- lang: java -->@FireAuthority(authorityTypes = AuthorityType.SALES_ORDER_DELETE, resultType=ResultTypeEnum.page)@RequestMapping(value="/save.spr", method=RequestMethod.POST)public ModelAndView save(String name) throws Exception { //some code}
9. Completed the

^_^

Subsequent

Also need a set of interface, in order to configure user rights, fortunately I have implemented this function, and the code is relatively simple, will be in the following blog detailed explanation.
Program Source code: https://github.com/eagle0445/sample/

© Copyright belongs to the authorTransferred from: http://my.oschina.net/kingfire/blog/102760

A method of SPRING-MVC permission control based on annotation

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.