Servlet very simple permission interception design processing

Source: Internet
Author: User

In the Java Web development encountered in the extremely simple permission control, the entire small project is divided into four or five kinds of user permissions role, so do not want to consider the use of the framework and database Building role table, menu table, Operation table, etc. to complete the authority design, but the use of reflection, annotations simple method to complete.
Core code
Baseservlet.java file

 PackageCom.zk.servlet;ImportJava.io.IOException;ImportJava.lang.reflect.Method;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportCom.zk.annotation.Permission;ImportCom.zk.bean.User;/** * Servlet base class * * @Description TODO * @author ZK * @version 1.0 * @date 2015-4- 9 pm 4:53:11 * /@SuppressWarnings("All") Public Abstract  class baseservlet extends httpservlet {    Private Static Final LongSerialversionuid =-6898295798172047477Lprotected void Service(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {/** * Ideas 1. Processing according to the method parameter 2. Use reflection call * 2 to add a simple permission to judge (can also be implemented through filter design interception) * Because this case does not require complex permission design, it does not use the sub- Do not build a few tables to save the role, menu, operation and other information, only use in the user table to add a field level 0 1,4,7 to process * 0: This user invalid (soft delete) equivalent has been deleted * 1: Normal visitor level without login is primarily front-end         Information View * 4: Membership level can be logged in, related operations * 7: Top-level Administrator operations * Some fields are reserved in the middle to do different permissions. * 3 The core idea of authority judgment: * 1> Build a Baseservlet parent class let the servlet inherit * 2> rewrite ser in Baseservlet The Vice method adds a custom annotation through reflection and by means of a method such as the following: "See Custom note file below" eg @Permission (level=3) * 3> in the service method through REQUEST.GETP The Armenter ("method") gets the corresponding method action name in the subclass, and the reflection gets the method name * above the annotation information level * 4> to the annotation information to The user's login status and the user's level status * for some operations need to log in or higher permission levels can be redirected to handle interception rights * 0 levels Ignore because 1 is normal permission to first determine whether the normal permission is the normal site visitor permissions * When the operation method of Leve for 1 release * not                Instructions for 1 require higher user rights *        Then first determine whether the login is not logged in the return login * Login successful to get the Leve status of the logged on user and request the method of operation level of permission class comparison * If the user's leve is less than the operation of the method, the interception is returned, but the method operation can be performed * * */        //Only dealt with the garbled problem of post, get self-processingReq.setcharacterencoding ("Utf-8");//Just deal with the character stream problem, byte stream self-processingResp.setcontenttype ("Text/html;charset=utf-8"); String methodName = Req.getparameter ("Method");//Determine if there is a method        if(MethodName = =NULL|| Methodname.trim (). IsEmpty ()) {Throw NewRuntimeException ("Kiss!" Please pass in the parameter of method "); } Class Clazz = This. GetClass (); Method method =NULL;Try{method = Clazz.getmethod (MethodName, Httpservletrequest.class, Httpservletresponse.class);//Note use annotations here to get the annotation information on each request methodPermission info = method.getannotation (permission.class);//If you get the annotation information            if(Info! =NULL) {intLevel = Info.level ();//Access required permission level for this operation                if(Level! =1) {//level is the default minimum level so skip the process is not required                    //Level!=1 description requires login and higher user rightsUser user = (user) req.getsession (). getattribute ("Backuser");//Determine if login                    if(Req.getsession (). getattribute ("Backuser") ==NULL) {String ContextPath = Getservletcontext (). Getcontextpath (); Resp.getwriter (). Print ("Pro, you have not logged in, please <a href= '"+ ContextPath +"/index.jsp ' target= ' _parent ' > Login </a>! ");return; }Else{//Login to successfully determine the level of the user and the level of this operation                        if(User.getlevel () < level) {String ContextPath = Getservletcontext (). Getcontextpath ()                            ; Resp.getwriter (). Print ("Sorry, you do not have permission to operate, please <a href= '"+ ContextPath +"/index.jsp ' target= ' _parent ' > login </a> apply for membership! ");return; }                    }                }            }        }Catch(Exception e) {E.printstacktrace ();Throw NewRuntimeException ("Kiss!" Wrong parameter for incoming method "); }Try{String result = (string) Method.invoke ( This, req, resp);if(Result! =NULL&&!result.trim (). IsEmpty ()) {Req.getrequestdispatcher (Result). Forward (req, resp); }        }Catch(Exception e) {E.printstacktrace ();Throw NewRuntimeException (e); }    }}

customizing annotation files Permission.java

 PackageCom.zk.annotation;ImportJava.lang.annotation.ElementType;ImportJava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/** * Custom permission annotations * @Description TODO * @author ZK * @version 1.0 * @date 2015-4-12 pm 9:34:46 * *@Retention(Retentionpolicy.runtime)@Target(Value={elementtype.method,elementtype.type}) Public@ interface Permission {    intLevel ();}

Example of the operation of a subclass servlet:

 PackageCom.zk.servlet;ImportJava.io.IOException;ImportJava.util.ArrayList;ImportJava.util.List;ImportJava.util.Map;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.beanutils.BeanUtils;ImportCom.zk.annotation.Permission;ImportCom.zk.bean.Customer;ImportCom.zk.bean.Message;ImportCom.zk.bean.MessageType;ImportCom.zk.bean.MessageTypeLev;ImportCom.zk.bean.PageBean;ImportCom.zk.bean.User;ImportCom.zk.service.CustomerService;ImportCom.zk.service.MessageService;ImportCom.zk.service.MessageTypeService;/** * and information-related controllers inherit custom Baseservlet * * @Description TODO * @author ZK * @version 1.0 *
     
       @date 2015-4-11 Morning 10:21:56 * *
      Public  class messageservlet extends baseservlet {    /** * Delete message by ID * @param request * @param response * @return * @thro WS Servletexception * @throws IOException * /    @Permission(Level =3)//Note: Annotations use different actions to set different values     PublicStringDeletebyid(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {String id = request.getparameter ("id"); String Pagecode = Request.getparameter ("Pagecode"); String totalpage = Request.getparameter ("Totalpage"); Messageservice cs =NewMessageservice (); Cs.deletebyid (ID);intpg =1;if(Integer.parseint (totalpage)% integer.parseint (pagecode) = =0) {if(Integer.parseint (Pagecode) >1) {pg = Integer.parseint (pagecode)-1; }Else{//Closed no information}        }return "/message?method=listmsg&pagecode="+ pg; }}

Attach the structure of user table design

-- ------------------------------Table structure for T_customer-- ----------------------------CREATE TABLE ' T_customer '(' id ' varchar( +) not NULL,' username ' varchar( -)DEFAULT NULL,' Gender ' varchar(Ten)DEFAULT NULL,' Birthday ' varchar( -)DEFAULT NULL,' Cellphone ' varchar( -)DEFAULT NULL,' Email ' varchar( +)DEFAULT NULL,' Love ' varchar( -)DEFAULT NULL,' type ' varchar( +)DEFAULT NULL,PRIMARY KEY(' id ')) Engine=innodbDEFAULTCharset=utf8;

Summary: Reflection annotations simply inherit unified processing. Things and ideas are rough, just to achieve the simple function of writing, hope to criticize the acceptance and advice, thank you.

Servlet very simple permission interception design processing

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.