jsp自定义标签

来源:互联网 发布:电商平台数据库架构 编辑:程序博客网 时间:2024/05/29 14:45
必须:一个tag类,一个tld;

第一步:
package com.sshcms.tag;

import java.io.IOException;

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


/**
*package_name com.sshcms.tag
*file_name AuthorityPermissionTag.java
*author zbw
*date 2012-3-27上午09:26:27
*/
public class AuthorityPermissionTag extends TagSupport {

private String param;


public String getParam() {
return param;
}

public void setParam(String param) {
this.param = param;
}


@Override
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
JspWriter out = pageContext.getOut();
try {
if("1".equals(param))
out.print("Hello World");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SKIP_BODY;
}
}




第二步:tld 文件,新建在WEB-INF下;/WEB-INF/tld/authority-permission.tld
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>

<tag>
<name>authority</name>
<tag-class>com.sshcms.tag.AuthorityPermissionTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>param</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

</taglib>





tld的基本属性:



第三步:在web.xml配置该标签
<jsp-config>
<taglib>
<taglib-uri>/UserTag-Authority</taglib-uri>
<taglib-location>/WEB-INF/tld/authority-permission.tld</taglib-location>
</taglib>
</jsp-config>



第四布:调用;
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib prefix="m" uri="/UserTag-Authority" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'tagTest.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<m:authority param="1"/>
</body>
</html>

shortname: 指定Tag Library默认的前缀名(prefix)
uri: 设定Tag Library的惟一访问表示符
标签元素用来定义一个标签,它的常见属性有:
name: 设定Tag的名字
tagclass: 设定Tag的处理类
bodycontent: 设定标签的主体(body)内容
empty:表示标签中没有body
JSP:表示标签的body中可以加入JSP程序代码
tagdependent:表示标签中的内容由标签自己去处理
标签属性元素用来定义标签的属性,它的常见属性有:
A.name:属性名称
B.required:属性是否必需的,默认为false
rtexprvalue:属性值是否可以为request-time表达式,也就是类似于<%=…%>的表达式



运行效果:


原创粉丝点击