Thứ Sáu, 5 tháng 9, 2014

Creating custom tags in jsp.

custom tag means user defined tags.JSP allows you to define your own tags .

To create your own tags You have to create three things
1.A java class
2..tld file
3.a simple jsp file to access information

I will Crate a simple jsp tag that give simple information like who created that tag.
note:
In order to create custom tags definition in java class you have to extend or implement some interfaces/classes of javax.servlet.jsp.tagext.* package.

1.customTag.java

This class will implement SimpleTagSupport class of  javax.servlet.jsp.tagext.* package

package com.shashikumar;
import java.io.IOException;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
public class customTag extends SimpleTagSupport {

   
    public void doTag() throws JspException, IOException {
        JspWriter writer=getJspContext().getOut();
        writer.print("This is a custom tag defined by shashikumar .l");
    }


}


In above doTag() is a overloaded method of SimpleTagSupport class.







2.Message.tlb



<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My first custom tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>com.shashikumar.customTag</tag-class>>
<body-content>empty</body-content>
</tag>

</taglib>

3.custom.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="my" uri="WEB-INF/Message.tld" %>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hi custom tag</title>
</head>
<body>
<my:MyMsg/>


</body>
</html>


output:

Không có nhận xét nào:

Đăng nhận xét