整理一份jsp自定义标签以及权限控制标签

jsp自定义标签使用场景因地制宜,可以实现自定义的标签输出功能也可以实现权限的管理

1:先定义标签类

1-1:页面输出标签

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();
}


/**

*设置标签的页面的上下文
*/


public void setPageContext(final PageContext pageContext) {
   this.pageContext = pageContext;
}


/**

*设置上一级标签
*/


public void setParent(final Tag parent) {
   this.parent = parent;
}


/**

*开始标签时的操作
*/


public int doStartTag() throws JspTagException {


   try {
    pageContext.getOut().println("Hello World!你好, 世界!<br/>");
   } catch (java.io.IOException e) {
    throw new JspTagException("IO Error: " + e.getMessage());
   }
   return SKIP_BODY; // 返回SKIP_BODY,表示不计算标签体
}


/**

*结束标签时的操作
*/


public int doEndTag() throws JspTagException {


   try {
    pageContext.getOut().write("Hello Java World!你好,Java 世界!");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return EVAL_PAGE;
}


/**

*release用于释放标签程序占用的资源,比如使用了数据库,那么应该关闭这个连接。
*/


public void release() {
}


public Tag getParent() {
   return parent;
}
}


1-2:权限管理标签

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 {
// 保存从XML文件中取到角色和页面元素的对应集合
private static ArrayList<ElementAndRole> roleList;
// 页面元素的名称
private String elementName;

public void setElementName(String str) {
this.elementName = str;
}


public int doAfterBody() throws JspException {
if (roleList == null) {
roleList = getList();
}

try {
// 如果认证通过就显示标签正文,否则跳过标签正文,就这么简单
if (isAuthentificated(elementName)) {
if (bodyContent != null) {
JspWriter out = bodyContent.getEnclosingWriter();
bodyContent.writeOut(out);
} else {
}
}
} catch (Exception e) {
throw new JspException();
}
return SKIP_BODY;
}


// 从XML配置文件中取到角色和页面元素的对应,保存到静态的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();
}
// 读取页面元素列表
NodeList elementList = doc.getElementsByTagName("htmlElement");
for (int i = 0; i < elementList.getLength(); i++) {
Element name = ((Element) elementList.item(i));
// 页面元素的名称
elementName = name.getAttribute("name");
// 该页面元素对应的有权限的角色的列表
NodeList rolNodeList = ((NodeList) name
.getElementsByTagName("roleName"));
for (int j = 0; j < rolNodeList.getLength(); j++) {
// 有权限的角色的名称
// roleName = ((Element)rolNodeList.item(j)).getNodeValue();
roleName = ((Element) rolNodeList.item(j)).getAttribute("name");
theList.add(new ElementAndRole(elementName, roleName));
}
}
return theList;
}


// 检查该角色是否有该页面元素的权限
private boolean isAuthentificated(String elementName) {
String roleName = "";
// 在用户登陆时把该用户的角色保存到session中,这里只是直接从SESSION中取用//户角色。
roleName = (String) this.pageContext.getSession().getAttribute("rolename");
// roleList包含elementName属性为elementName,roleName属性为roleName的//ElementAndRole对象,则该角色有该页面元素的权限
if (roleList.contains(new ElementAndRole(elementName, roleName))) {
return true;
}
return false;
}


// 表示角色和页面元素的对应的关系的内部类
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:实现了标签的定义类之后,就是定义标签的tld文件

<?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>

权限管理标签实验性测试权限配置文件

<?xml version="1.0" encoding="UTF-8"?>
<security>
<htmlElement name="employeedetail">
<roleName name="common"/>
<roleName name="admin"/>
</htmlElement>
<htmlElement name="employeemodify">
<roleName name="admin"/>
</htmlElement>
</security>


3:web.xml中引入标签

<!--自定义标签 -->
 <jsp-config>
<taglib>
<taglib-uri>http://mytag</taglib-uri>
<taglib-location>
/WEB-INF/tagconfig/mytld.tld
</taglib-location>
</taglib>
</jsp-config>

这样,标签定义完毕。

4:测试

4-1:indxe.jsp展示hello功能标签以及权限-admin与common角色标签

<%@ taglib uri="http://mytag" prefix="mytag"%>
<%@ page contentType="text/html ; charset=UTF-8"%>


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


<form name="form1">
<table width="600" 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>以下的内容从Taglib中显示:</p>
<mytag:hello />
</body>
</html>

4-2:index1标签展现common角色标签

<%@ taglib uri="http://mytag" prefix="mytag"%>
<%@ page contentType="text/html ; charset=UTF-8"%>
<html>
<head>
<title>test</title>
</head>
<body>
<form name="form1">
<table width="600" 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:运行结果

admin角色

整理一份jsp自定义标签以及权限控制标签

common角色

整理一份jsp自定义标签以及权限控制标签

至此结束,实现方式粗略,权当演示。

你可能感兴趣的:(整理一份jsp自定义标签以及权限控制标签)