Organize a JSP custom label and permission control label

Source: Internet
Author: User
Tags control label tld

JSP custom tags use the scene to local conditions, you can implement a custom label output function can also achieve the management of permissions

1: Define Label class first

1-1: Page Output tab

Package Com.suyin.web.jspsectag;

Import java.io.IOException;
Import javax.servlet.jsp.JspTagException;
Import Javax.servlet.jsp.PageContext;
Import Javax.servlet.jsp.tagext.Tag;


public class Hellotag implements TAG {
Private PageContext PageContext;
Private Tag parent;
Public Hellotag () {
Super ();
}


/**
*
* Set the context of the label's page
*/


public void Setpagecontext (final PageContext PageContext) {
This.pagecontext = PageContext;
}


/**
*
* Set up a top level label
*/


public void SetParent (final Tag parent) {
This.parent = parent;
}


/**
*
* Action when starting the tag
*/


public int doStartTag () throws Jsptagexception {


try {
Pagecontext.getout (). println ("Hello world! hello, world! <br/> ");
} catch (Java.io.IOException e) {
throw new Jsptagexception ("IO Error:" + e.getmessage ());
}
return skip_body; Returns Skip_body, indicating that the label body is not calculated
}


/**
*
* Action when closing the tag
*/


public int Doendtag () throws Jsptagexception {


try {
Pagecontext.getout (). Write ("Hello java world! hello, java world!"). ");
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
return eval_page;
}


/**
*
*release is used to release resources used by the label program, such as using a database, the connection should be closed.
*/


public void release () {
}


Public Tag getParent () {
return parent;
}
}


1-2: Rights Management tab

Package Com.suyin.web.jspsectag;


Import Java.io.File;
Import java.util.ArrayList;


Import javax.servlet.jsp.JspException;
Import Javax.servlet.jsp.JspWriter;
Import Javax.servlet.jsp.tagext.BodyTagSupport;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import org.w3c.dom.NodeList;


@SuppressWarnings ("Serial")
public class Jspsecuritytag extends Bodytagsupport {
Save the corresponding collection of roles and page elements from the XML file
private static arraylist<elementandrole> rolelist;
The name of the page element
Private String elementname;

public void Setelementname (String str) {
This.elementname = str;
}


public int doafterbody () throws Jspexception {
if (rolelist = = null) {
Rolelist = GetList ();
}

try {
If authentication is displayed by the label body, otherwise skip the label body, it is so simple
if (isauthentificated (elementname)) {
if (bodycontent! = null) {
JspWriter out = Bodycontent.getenclosingwriter ();
Bodycontent.writeout (out);
} else {
}
}
} catch (Exception e) {
throw new Jspexception ();
}
return skip_body;
}


From the XML configuration file to the corresponding role and page elements, save to the static ArrayList
Private Arraylist<elementandrole> getList () {
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
Documentbuilder db = null;
Document doc = null;
String elementname;
String RoleName;
arraylist<elementandrole> thelist = new arraylist<elementandrole> ();
try {
db = Dbf.newdocumentbuilder ();
} catch (Exception e) {
E.printstacktrace ();
}


try {
doc = Db.parse (new File (This.getclass (). GetResource ("/"). GetPath () + "Props/security.xml"));
} catch (Exception e) {
E.printstacktrace ();
}
Reading a list of page elements
NodeList elementlist = Doc.getelementsbytagname ("HtmlElement");
for (int i = 0; i < elementlist.getlength (); i++) {
Element name = (element) Elementlist.item (i));
The name of the page element
ElementName = Name.getattribute ("name");
A list of the roles that the page element corresponds to that have permissions
NodeList rolnodelist = ((NodeList) name
. getElementsByTagName ("RoleName"));
for (int j = 0; J < Rolnodelist.getlength (); j + +) {
Name of the role with permissions
RoleName = (Element) Rolnodelist.item (j)). Getnodevalue ();
RoleName = (Element) Rolnodelist.item (j)). GetAttribute ("name");
Thelist.add (New Elementandrole (ElementName, roleName));
}
}
return thelist;
}


Checks if the role has permission for the page element
Private Boolean isauthentificated (String elementname) {
String roleName = "";
The user's role is saved to the session when the user logs in, and the role is only taken directly from the session.
RoleName = (String) this.pageContext.getSession (). getattribute ("RoleName");
Rolelist contains a//elementandrole object with the ElementName property of Elementname,rolename property as RoleName, the role has permission for the page element
if (Rolelist.contains (New Elementandrole (ElementName, RoleName))) {
return true;
}
return false;
}


Internal classes that represent the corresponding relationships of roles and page elements
Class Elementandrole {
String elementname;
String RoleName;


Public Elementandrole (String elementname, String roleName) {
This.elementname = elementname;
This.rolename = RoleName;
}


public boolean equals (Object obj) {
Return ((elementandrole) obj. Elementname.equals (this.elementname) && ((elementandrole) obj). roleName
. Equals (This.rolename));
}
}
}


2: After implementing the label definition class, it is the TLD file that defines the label

<?xml version= "1.0" encoding= "UTF-8"?>
<taglib xmlns= "Http://java.sun.com/xml/ns/j2ee" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
version= "2.0" >
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<description>this si....</description>
<short-name>myT</short-name>
<uri>http://mytag</uri>


<tag>
<description>extends tagsupport</description>
<name>hello</name>
<tag-class>com.suyin.web.jspsectag.HelloTag</tag-class>
<body-content>jsp</body-content>
</tag>


<tag>
<name>JspSecurity</name>
<tagclass>com.suyin.web.jspsectag.JspSecurityTag</tagclass>
<info>
Jspsecuritytag
</info>
<attribute>
<name>elementName</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>


</taglib>

Rights Management label Experimental test permission profile

<?xml version= "1.0" encoding= "UTF-8"?>
<security>
<rolename name= "Common"/>
<rolename name= "admin"/>
<rolename name= "admin"/>
</security>


Introduction of tags in 3:web.xml

<!--custom Labels--
<jsp-config>
<taglib>
<taglib-uri>http://mytag</taglib-uri>
<taglib-location>
/web-inf/tagconfig/mytld.tld
</taglib-location>
</taglib>
</jsp-config>

This way, the label definition is complete.

4: Test

4-1:indxe.jsp Show Hello feature tags and permissions-admin and common role tags

<%@ taglib uri= "Http://mytag" prefix= "MyTag"%>
<%@ page contenttype= "text/html; Charset=utf-8 "%>


<title>first cumstomed tag</title>
<body>


<form name= "Form1" >
<table width= "border=" 0 "cellspacing=" 0 "cellpadding=" 2 ">
<tr>
<td><mytag:jspsecurity elementname= "Employeedetail" >
<input type= "button" name= "detail" value= "common?" >
</mytag:JspSecurity> <mytag:jspsecurity elementname= "Employeemodify" >
<input type= "button" name= "Modify" value= "admin" >
</mytag:JspSecurity></td>
</tr>
</table>
<br>
</form>


<p> The following content is displayed from Taglib:</p>
<mytag:hello/>
</body>

4-2:INDEX1 tags Show Common role tags

<%@ taglib uri= "Http://mytag" prefix= "MyTag"%>
<%@ page contenttype= "text/html; Charset=utf-8 "%>
<title>test</title>
<body>
<form name= "Form1" >
<table width= "border=" 0 "cellspacing=" 0 "cellpadding=" 2 ">
<tr>
<td><mytag:jspsecurity elementname= "Employeedetail" >
<input type= "button" name= "detail" value= "common" >
</mytag:JspSecurity> <mytag:jspsecurity elementname= "Employeemodify" >
<input type= "button" name= "Modify" value= "admin" >
</mytag:JspSecurity></td>
</tr>
</table>
<br>
</form>
</body>

5: Run Results

Admin Role

Common role

At this end, the implementation of a rough way, right when the demo.

Organize a JSP custom label and permission control label

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.