`

JSP 自定义标签

    博客分类:
  • JSP
 
阅读更多

一、在WEB-INF下新建 test-tags.tld文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
	<tlib-version>1.0</tlib-version>
	<jsp-version>1.2</jsp-version>
	<short-name>test</short-name>
	<uri>/test-tags</uri>
	<tag>
		<description>用户是否有相应权限访问该模块</description>
		<name>perm</name>
		<tag-class>test.TestPermTag</tag-class>
		<body-content>jsp</body-content>
		<attribute>
			<name>id</name>
			<required>true</required>
			<rtexprvalue>false</rtexprvalue>
		</attribute>
		<attribute>
			<name>mode</name>
			<required>false</required>
			<rtexprvalue>false</rtexprvalue>
		</attribute>
		<attribute>
			<name>variable</name>
			<required>false</required>
			<rtexprvalue>false</rtexprvalue>
		</attribute>
	</tag>
</taglib>

 二、新建相应类

package test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class TestPermTag extends TagSupport {

	private static final long serialVersionUID = 7366546229421462048L;

	private String id = null;

	private String mode = "session";

	private String variable = "allPerm";

	public void setId(String id) {
		this.id = id;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public void setVariable(String variable) {
		this.variable = variable;
	}

	@Override
	/**
	 * EVAL_BODY_INCLUDE:显示标签间文字
	 * SKIP_BODY:不显示标签间文字
	 */
	public int doStartTag() throws JspException {
		if (id != null && !id.trim().equals("") && mode.equalsIgnoreCase("session")) {
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			HttpSession session = httpServletRequest.getSession();
			if (session != null) {
				Object perms = session.getAttribute(variable);
				if (perms != null) {
					id = "," + id + ",";
					if (perms.toString().indexOf(id) >= 0) {
						return EVAL_BODY_INCLUDE;
					}
				}
			}
		}
		return SKIP_BODY;
	}
}

 三、JSP页面

<%@taglib uri="/test-tags" prefix="test" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<test:perm id="a">a</test:perm>

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics