您的位置:首页 > 编程语言 > Java开发

java自定义标签的简单例子

2016-05-19 17:54 363 查看

1、处理类

package com;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public class TestTag extends TagSupport {

private String longtime;

public String getLongtime() {
return longtime;
}

public void setLongtime(String longtime) {
this.longtime = longtime;
}

@Override
public int doStartTag() throws JspException {

long l = 0l;
if (null != longtime && "".equals(longtime)) {
l = Long.parseLong(longtime);
}
Date date = new Date(l);

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String date_string = sd.format(date);
try {
super.pageContext.getOut().print(date_string);
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}

}

 2、tld文件,放在WEB-INF下面

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>ct</short-name>
<uri>/dateConvert</uri>

<tag>
<name>longStr</name>
<tag-class>com.TestTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>longtime</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

 

3、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<jsp-config>
<taglib>
<taglib-uri>/dateConvert</taglib-uri>
<taglib-location>dateConvert.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>

 4/jsp引用

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/dateConvert" prefix="ct"%>
<%
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 'index.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><ct:longStr longtime="1314842011312"></ct:longStr>

</body>
</html>

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: