The OA permission module displays different action buttons according to user rights _J2SE

Source: Internet
Author: User

Several previous Bowen introduced how to implement different interface menus according to different user rights, which belongs to the coarse granularity division in the permission module. If we want to control a user's permissions to the specific button should be how to implement it. This blog post is a brief introduction for everyone.


First, the situation import

The following figure is a module in my system with three permission actions to add delete modifications, as shown in the figure:

Now I've got a total user, I don't want him to have add and modify permissions how to do it.


Second, the concrete realization


1. First of all, let's take a look at the prepared JSP interface


<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>  


2. Rewrite the <s:a>tag label in Struts2


We create a new class that corresponds to the same a tag in the bottom, so that if the compiler can find the class we need under our classpath path, we won't go looking for it in the core package of struts. After creating the appropriate packages and classes, we rewrite the Doendtag method:

Package org.apache.struts2.views.jsp.ui;
Import Org.apache.struts2.components.Anchor;

Import org.apache.struts2.components.Component;

Import Cn.itcast.oa.domain.User;

Import Com.opensymphony.xwork2.util.ValueStack; /** * @see Anchor */public class Anchortag extends Abstractclosingtag {private static final long Serialversionuid =

	-1034616578492431113l;
	protected String href;
	protected String includeparams;
	protected String Scheme;
	protected String Action;
	protected String namespace;
	protected String method;
	protected String encode;
	protected String Includecontext;
	protected String Escapeamp;
	protected String Portletmode;
	protected String WindowState;
	protected String Portleturltype;
	protected String Anchor;

	protected String Forceaddschemehostandport; Overwrite the Doendtag method @Override public int Doendtag () throws Jspexception {//The current logged-on user Username = (user) pagecontext.getses

		Sion (). getattribute ("user"); The permission URL for the link currently being displayed//at the beginning Plus '/' String privurl = '/' + Action 
		if (User.hasprivilegebyurl (Privurl)) {//normal generates and displays the hyperlink label, and continues to execute the code back in the page return Super.doendtag (); 
		else {//do not generate and display hyperlink labels, just continue to execute the following code return eval_page on the page; } public Component Getbean (Valuestack stack, httpservletrequest req, httpservletresponse Res) {return new Anchor (s)
	Tack, req, res);

		} protected void Populateparams () {super.populateparams ();
		Anchor tag = (anchor) component;
		tag.sethref (HREF);
		Tag.setincludeparams (Includeparams);
		Tag.setscheme (scheme);
		Tag.setvalue (value);
		Tag.setmethod (method);
		Tag.setnamespace (namespace);
		Tag.setaction (action);
		Tag.setportletmode (Portletmode);
		Tag.setportleturltype (Portleturltype);
		Tag.setwindowstate (WindowState);

		Tag.setanchor (anchor);
		if (encode!= null) {Tag.setencode (boolean.valueof (encode). Booleanvalue ());
		} if (Includecontext!= null) {Tag.setincludecontext (boolean.valueof (Includecontext). Booleanvalue ()); } if (Escapeamp!= null) {Tag.setescapeamp (Boolean. valueof (Escapeamp). Booleanvalue ()); } if (Forceaddschemehostandport!= null) {Tag.setforceaddschemehostandport (boolean.valueof Forceaddschemehostandpor
		T). Booleanvalue ());
	} public void Sethref (String href) {this.href = href;
	} public void Setencode (String encode) {this.encode = encode;
	} public void Setincludecontext (String includecontext) {this.includecontext = Includecontext;
	} public void Setescapeamp (String escapeamp) {this.escapeamp = Escapeamp;
	public void Setincludeparams (String name) {includeparams = name;
	The public void Setaction (String action) {this.action = action;
	} public void Setnamespace (String namespace) {this.namespace = namespace;
	public void Setmethod (String method) {This.method = method;
	public void SetScheme (String scheme) {this.scheme = scheme;
	public void SetValue (String value) {this.value = value; } public void Setportletmode (String portletmode) {this.portletmode = Portletmode;
	} public void Setportleturltype (String portleturltype) {this.portleturltype = Portleturltype;
	} public void Setwindowstate (String windowstate) {this.windowstate = WindowState;
	public void Setanchor (String anchor) {this.anchor = anchor; } public void Setforceaddschemehostandport (String forceaddschemehostandport) {this.forceaddschemehostandport = ForceA
	Ddschemehostandport;
 }
}

3. In the user entity, add methods that determine whether or not permissions are based on the URL method


In the last post we have mentioned that the user login using the user's permission information to determine the user can access the menu list, and put them in the application domain, we judge the time from the application domain of the user has the right to the URL of the menu to get, and then recycle convenient To compare whether our users have the right to do so, if they have the tag tag normally executed, and if they do not, hide the label. The code is as follows:

Package cn.itcast.oa.domain;
Import java.util.Collection;
Import Java.util.HashSet;

Import Java.util.Set;

Import Com.opensymphony.xwork2.ActionContext;
	/** * @author TYG * * */public class user implements java.io.serializable{private Long ID;
	Private Department Department;

	Private set<role> roles = new hashset<role> (); Private String LoginName; Login name private String password; Password private String name; Real name private String gender; Gender private String PhoneNumber; Phone number private String email; e-mail private String description;
		Description/** * Determines whether the user has the specified name permission * * @param name * @return/public boolean hasprivilegebyname (String name) {
		Super Admin has permissions if (ISAdmin ()) {return true; }//Ordinary user to determine whether to include this permission for (role Role:roles) {for (Privilege priv:role.getPrivileges ()) {if Priv.getname (
				). Equals (name) {return true;
	}} return false; /** * Determines whether the user has permission to specify a URL * * @param privurl * @reTurn */public boolean hasprivilegebyurl (String privurl) {//admin has permission if (ISAdmin ()) {return true;
		//Remove the parameter int pos = Privurl.indexof ("?") at the back. if (pos >-1) {//if present.
		Then intercept the following parameters Privurl = privurl.substring (0, POS); //Remove the UI suffix if (privurl.endswith ("UI") in the URL {///if the URL before the UI is intercepted at the end of the UI Privurl = privurl.substring (0, Privurl.lengt
		H ()-2); //If this URL does not require control, the logged-on user can use the collection<string> Allprivilegeurls = (collection<string>) actioncontext.getc
		Ontext (). Getapplication (). Get ("Allprivilegeurls");
		if (!allprivilegeurls.contains (Privurl)) {return true; else {//ordinary user to determine whether to include this permission for (role Role:roles) {for (Privilege priv:role.getPrivileges ()) {if (PRI
					Vurl.equals (Priv.geturl ()) {return true;
		}} return false;
	}/** * To determine if the user is a super Administrator * * @return * * * public boolean ISAdmin () {return "admin". Equals (LoginName);
	Public Long GetId () {return id; } public void SETID (Long id) {this.id = ID;
	Public Department getdepartment () {return Department;
	public void Setdepartment (Department Department) {this.department = Department;
	Public set<role> GetRoles () {return roles;
	public void Setroles (set<role> roles) {this.roles = roles;
	Public String Getloginname () {return loginName;
	} public void Setloginname (String loginName) {this.loginname = LoginName;
	Public String GetPassword () {return password;
	} public void SetPassword (String password) {this.password = password;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public String Getgender () {return gender;
	} public void Setgender (String gender) {This.gender = gender;
	Public String Getphonenumber () {return phonenumber;
	} public void Setphonenumber (String phonenumber) {this.phonenumber = PhoneNumber;
	Public String Getemail () {return email;
}
	public void Setemail (String email) {this.email = email;
	Public String GetDescription () {return description;
	} public void SetDescription (String description) {this.description = description;
 }

}

Third, the right to intercept each request


The above two steps of operation, only shows if the user login, display and its rights corresponding to the action button, only to achieve the interface control effect, in fact, if the browser to enter the corresponding URL, or access to the corresponding permissions, then how should we deal with this kind of situation? Interceptors are certainly a good idea. If the user has not logged in, then jump to the login interface, otherwise, according to the URL to determine the user's permissions, access to the right, no jump to the error page.


1. Writing interceptors


Package cn.itcast.oa.util;

Import Cn.itcast.oa.domain.User;
Import Com.opensymphony.xwork2.ActionContext;
Import com.opensymphony.xwork2.ActionInvocation;

Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class Checkprivilegeinterceptor extends Abstractinterceptor {//to intercept all requested URLs by public String intercept (ACTIONINV Ocation invocation) throws Exception {//obtain information User user = (user) Actioncontext.getcontext (). GetSession (). Get ("user") ;
		Current Logged-on user String namespace = invocation.getproxy (). GetNamespace ();
		String actionname = Invocation.getproxy (). Getactionname (); String Privurl = namespace + actionname; corresponding permission URL//If not logged in if (user = = null) {if (Privurl.startswith ("/user_login")) {//"/user_loginui", "/user_login
			"//If you are going to login, release return Invocation.invoke ();"
			else {//If you are not logged in, go to the login page return "Loginui"; }///If you are logged in, judge permissions else {if (User.hasprivilegebyurl (Privurl)) {//if permission is granted, release return Invocation.invoke ()
	;		else {//If there is no permission, go to the prompt page return "Noprivilegeerror";
 }
		}
	}
}

2. Configuring in Struts.xml Files


    	<interceptors>
    		<!--declaring interceptors-->
    		<interceptor name= "Checkprivilege" class= " Cn.itcast.oa.util.CheckPrivilegeInterceptor "></interceptor>
    		
    		<!--redefine the default interceptor stack-->
    		< Interceptor-stack name= "Defaultstack" >
    			<interceptor-ref name= "Checkprivilege" ></interceptor-ref >
    			<interceptor-ref name= "Defaultstack" ></interceptor-ref>
    		</interceptor-stack>
    	</interceptors>


		<!--global result configuration-->
		<global-results>
			<result name= " Loginui ">/WEB-INF/jsp/userAction/loginUI.jsp</result>
			<result name=" Noprivilegeerror ">/ Noprivilegeerror.jsp</result>
		</global-results>


Summarize:

This is part of the permission module on the right to control very classic implementation, the main knowledge are:

1. Re-struts2 the Doendtag method of tag tags;

2. Add a method to control user rights based on the URL in the user entity;

3. According to the URL to determine the rights of the method of the operation of the string, the previous study and reviewed again ' (*∩_∩*)

4. Use the interceptor to intercept all actions and perform the appropriate action

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.