JSP with Custom Tags - PowerPoint PPT Presentation

1 / 19
About This Presentation
Title:

JSP with Custom Tags

Description:

JSP with Custom Tags Blake Adams 2-19-2003 – PowerPoint PPT presentation

Number of Views:139
Avg rating:3.0/5.0
Slides: 20
Provided by: westgaEdu
Learn more at: https://www.westga.edu
Category:
Tags: jsp | custom | java | servlet | tags

less

Transcript and Presenter's Notes

Title: JSP with Custom Tags


1
JSP with Custom Tags
  • Blake Adams
  • 2-19-2003

2
Introduction
  • Advanced Java Server Pages
  • Custom Tags
  • Keyterms
  • - Tag Library Descriptor(TLD)
  • - Tag Libraries
  • - Tag Handlers
  • - javax.servlet.jsp.tagext (the Tag Package
    illustrated on p.24)
  • - doStartTag, doEndTag, release
  • - Tag Attributes

3
What Is a Custom Tag?
  • A custom tag is a user-defined JSP language
    element. When a JSP page containing a custom tag
    is translated into a servlet, the tag is
    converted to operations on an object called a tag
    handler. The Web container then invokes those
    operations when the JSP page's servlet is
    executed.
  • Be customized via attributes passed from the
    calling page.
  • Access all the objects available to JSP pages.
  • Modify the response generated by the calling
    page.
  • Communicate with each other.
  • Be nested within one another, allowing for
    complex interactions within a JSP page
  • - Java.sun.com Java Web Services Tutorial

4
Creating a Simple Custom Tag
  • Add a taglib directive to JSP file using the tag
  • Create a tag library descriptor (.tld)
  • Implement tag handlers to extend TagSupport and
    override doStartTag() or doEndTag()

5
Example 1 page counter Tag with no attributes
  • The JSP File
  • lthtmlgtltheadgtlttitlegtA Counter Pagelt/titlegtlt/headgtltb
    odygt
  • lt_at_ taglib uri /WEB-INF/tlds/counter.tld
    prefixutil gt
  • This page has been accessed ltbgtltutilcounter/gtlt/bgt
    times.
  • lt/bodygtlt/htmlgt
  • - taglib identifies location of tag library
    descriptor. Tablib directives also require a
  • -prefix attribute that specifies the prefix used
    to access the librarys tags in this example
    its util

6
Example 1 page counter
  • The TLD File
  • lt?xml version"1.0" encoding"ISO-8859-1" ?gt
  • lt!DOCTYPE taglib PUBLIC
  • "-//Sun Microsystems, Inc.//DTD JSP Tag Library
    1.1//EN"
  • "http//java.sun.com/j2ee/dtds/web-jsptaglibrary
    _1_1.dtd"gt
  • lttaglibgt
  • lttlibversiongt1.0lt/tlibversiongt ltjspversiongt1.1lt/j
    spversiongt
  • ltshortnamegtSun Microsystems PressTag
    Librarylt/shortnamegt
  • ltinfogtExample 1-2b from book single counter
    taglt/infogt
  • lttaggt (definition identifier)
  • ltnamegtcounterlt/namegt
  • lttagclassgttags.CounterTaglt/tagclassgt //tag
    handler
  • ltbodycontentgtemptylt/bodycontentgt
  • lt/taggt
  • lt/taglibgt
  • - A tag library descriptor is an XML document
    that defines a tag library and its tags.
    Additional tag elements are defined in book on
    p.11

7
Example 1 page counter
  • Tag HandlerThe Servlet - Imports
  • package tags
  • import java.io.File
  • import java.io.FileReader
  • import java.io.FileWriter
  • import java.io.IOException
  • import javax.servlet.jsp.JspException
  • import javax.servlet.jsp.tagext.TagSupport
    //includes doStartTag() and doEndTag(), both
    return ints.
  • import javax.servlet.http.HttpServletRequest

8
Example 1 page counter
  • The Servlet doStartTag
  • public class CounterTag extends TagSupport
  • private int count 0
  • private File file null //created on local
    drive to store visits info
  • public int doStartTag() throws JspException
  • try
  • checkFile() //soon to be defined
  • readCount() //soon to be defined
  • pageContext.getOut().print(count)//thi
    s is output of the tag, also increments count
  • catch(java.io.IOException ex)
  • throw new JspException(ex.getMessage())
  • return SKIP_BODY // doStartTag should retur
    n this constant when
  •     // tag has no body.  SKIP_BODY inherited
    from javax.servlet.jsp.tagext.Tag 

9
Example 1 page counter
  • The Servlet doEndTag and checkFile
  • public int doEndTag() throws JspException
  • saveCount()//defined later
  • return EVAL_PAGE//continue with rest of
    jsp page
  • //if a file named with the same name as the
    jsp page with a .counter suffix does not exist,
    one is created.
  • private void checkFile() throws JspException,
    IOException
  • if(file null)
  • file new File(getCounterFilename())
  • count 0
  • if(!file.exists())
  • file.createNewFile()
  • saveCount()

10
Example 1 page counter
  • The Servlet getCounterFileName and saveCount
  • //checks file name and appends .counter, used
    above
  • private String getCounterFilename()
  • HttpServletRequest req (HttpServletRequest
    )pageContext.getRequest()
  • String servletPath req.getServletPath()
  • String realPath pageContext.getServletC
    ontext().getRealPath(servletPath)
  • return realPath ".counter"
  • //saves count returned by counter to file
  • private void saveCount() throws JspException
  • try
  • FileWriter writer new
    FileWriter(file)
  • writer.write(count)
  • writer.close()
  • catch(Exception ex)
  • throw new JspException(ex.getMessage())

11
Example 1 page counter
  • The Servlet readCount
  • //reads count from file stored on local drive
  • private void readCount() throws JspException
  • try
  • FileReader reader new
    FileReader(file)
  • count reader.read()
  • reader.close()
  • catch(Exception ex)
  • throw new JspException(ex.getMessage())
  • //class CounterTag

12
Example 1 page counter
  • Indirectily specifying TLD in WEB-INF/web.xml
    file
  • //in the JSP file
  • lt_at_ taglib uricounters prefixutil gt
  • //in web.xml
  • lttaglibgt
  • lttaglib-urigtcounterlttaglib-urigt
  • lttaglib-locationgt/WEB-INF/tlds/counter.tldlt/tagli
    b-locationgt
  • lt/taglibgt

13
Adding an attribute to a tag
  • Add the attribute, where applicable, to existing
    tags in JPS files
  • Add an attribute tag to the TLD
  • Implement a getAttr method to the tag handler
    where attr is the appropriate corrosponding
    attribute compliant with their JavaBeans API
  • It is also common to implement a getter method in
    the tag handler.

14
Example 2 Registration Tag with attributes
  • The JSP File
  • lthtmlgtltheadgtlttitlegtRegistration
    Pagelt/titlegtlt/headgt
  • ltbodygt
  • lt_at_ taglib uri'WEB-INF/tlds/html.tld'
    prefix'html'gt
  • lth2gtPlease Registerlt/h2gtlthrgt
  • ltform action'lt response.encodeURL("CentralServl
    et") gt 'method'post'gt
  • lttablegt
  • lttrgtlttdgt First Name lt/tdgt
  • lttdgtltinput type'text' size15
    name'firstName'
  • value'lthtmlrequestParameter
    property"firstName"/gt'gt
  • lt/tdgtlt/trgt
  • lttrgtlttdgt Last Name lt/tdgt
  • lttdgtltinput type'text' size15
    name'lastName'
  • value'lthtmlrequestParameter
    property"lastName"/gt'gt
  • lt/tdgt lt/trgt
  • lttrgtlttdgt E-mail Address lt/tdgt
  • lttdgtltinput type'text' size25
    name'emailAddress'
  • value'lthtmlrequestParameter
    property"emailAddress"/gt'gt
  • lt/tdgtlt/trgt

15
Example 2 Registration
  • ActionRegister.java file
  • package com.sunpress.actions
  • import java.io.
  • import javax.servlet.
  • import javax.servlet.http.
  • import com.sunpress.actions.routers.
  • import com.sunpress.beans.
  • public class RegisterAction extends
    ServletActionImpl
  • private String first, last, email
  • public synchronized void perform(HttpServlet
    servlet, HttpServletRequest req,
    HttpServletResponse res) throws IOException,
    ServletException
  • readParameters(req)
  • if(inputComplete() validEmailAddress())
  • ServletContext context servlet.getServletCont
    ext()
  • RegistrationDB regDB (RegistrationDB) cont
    ext.getAttribute("register")
  • User user regDB.addUser(first, last, email)
  • req.getSession().setAttribute("user", user)
  • success true

16
Example 2 Registration
  • ActionRegister.java file continued
  • else
  • success false
  • public Router createRouter()
  • return new RegisterRouter()
  • public boolean validEmailAddress()
  • return email.endsWith(".com")
    email.endsWith(".net")
  • email.endsWith(".org") email.endsWith(".ed
    u")
  • public boolean inputComplete()
  • return !first.equals("") !last.equals("")
  • !email.equals("")
  • private void readParameters(HttpServletRequest
    req)
  • first req.getParameter("firstName")
  • last req.getParameter("lastName")

17
Example 2 Registration
  • The TLD File
  • lt?xml version"1.0" encoding"ISO-8859-1" ?gt
  • lt!DOCTYPE taglib PUBLIC
  • "-//Sun Microsystems, Inc.//DTD JSP Tag Library
    1.1//EN"
  • "http//java.sun.com/j2ee/dtds/web-jsptaglibrary
    _1_1.dtd"gt
  • lttaglibgt
  • lttlibversiongt1.0lt/tlibversiongt
  • ltjspversiongt1.1lt/jspversiongt
  • ltshortnamegtSun Microsystems Press
    Exampleslt/shortnamegt
  • lttaggt
  • ltnamegtrequestParameterlt/namegt
  • lttagclassgttags.GetRequestParameterTaglt/tagclassgt
  • ltbodycontentgtemptylt/bodycontentgt
  • ltattributegt
  • ltnamegtpropertylt/namegt//name of attribute
  • ltrequiredgttruelt/requiredgt//true, thus must be
    specified
  • ltrtexprvaluegttruelt/rtexprvaluegt//true, thus
    can be specified lt/attributegt //with a
    JSP request time attribute
  • lt/taggt

18
Example 2 Registration
  • The Servlet action is diagramed on p 19
  • package tags
  • import javax.servlet.ServletRequest
  • import javax.servlet.jsp.JspException
  • import javax.servlet.jsp.tagext.TagSupport
  • public class GetRequestParameterTag extends
    TagSupport
  • private String property
  • public void setProperty(String property)
    //invoked before deStartTag
  • this.property property
  • public int doStartTag() throws JspException
  • ServletRequest req pageContext.getRequest(
    )
  • String value req.getParameter(property)
  • try
  • pageContext.getOut().print(value null
    ? "" value)//accesses page info
  • catch(java.io.IOException ex)
  • throw new JspException(ex.getMessage())

19
The Tag Package
  • All tag handlers implement the Tag interface,
    most by extending either TagSupport or
    BodyTagSupport
  • - TagSupport extensions are restricted to
    ignoring body content or passing it through
    unchanged.
  • - BodyTagSupport can manipulate their body
    content.
  • Tag Package is illustrated on p24
Write a Comment
User Comments (0)
About PowerShow.com