Download presentation
Presentation is loading. Please wait.
Published byRoss Fowler Modified over 9 years ago
1
1 JSP with Custom Tags Blake Adams 2-19-2003
2
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
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
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
5 Example 1 – page counter Tag with no attributes The JSP File A Counter Page This page has been accessed times. - taglib identifies location of tag library descriptor. Tablib directives also require a: -prefix attribute that specifies the prefix used to access the library’s tags – in this example it’s ‘util’
6
6 Example 1 – page counter The TLD File <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1 Sun Microsystems PressTag Library Example 1-2b from book – single counter tag (definition identifier) counter tags.CounterTag //tag handler empty - A tag library descriptor is an XML document that defines a tag library and it’s tags. Additional tag elements are defined in book on p.11
7
7 Example 1 – page counter Tag Handler:The 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
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);//this is output of the tag, also increments count } catch(java.io.IOException ex) { throw new JspException(ex.getMessage()); } return SKIP_BODY; // doStartTag should return this constant when } // tag has no body. SKIP_BODY inherited from javax.servlet.jsp.tagext.Tag
9
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
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.getServletContext().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
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
12 Example 1 – page counter Indirectily specifying TLD in WEB- INF/web.xml file //in the JSP file… //in web.xml … counter /WEB-INF/tlds/counter.tld
13
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
14 Example 2 – Registration Tag with attributes The JSP File Registration Page Please Register 'method='post'> First Name: <input type='text' size=15 name='firstName' value=' '> Last Name: <input type='text' size=15 name='lastName' value=' '> E-mail Address: <input type='text' size=25 name='emailAddress' value=' '>
15
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.getServletContext(); RegistrationDB regDB = (RegistrationDB) context.getAttribute("register"); User user = regDB.addUser(first, last, email); req.getSession().setAttribute("user", user); success = true; }
16
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(".edu"); } public boolean inputComplete() { return !first.equals("") && !last.equals("") && !email.equals(""); } private void readParameters(HttpServletRequest req) { first = req.getParameter("firstName"); last = req.getParameter("lastName"); email = req.getParameter("emailAddress"); }
17
17 Example 2 – Registration The TLD File <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1 Sun Microsystems Press Examples requestParameter tags.GetRequestParameterTag empty property //name of attribute true //true, thus must be specified true //true, thus can be specified //with a JSP request time attribute
18
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()); } return SKIP_BODY; }
19
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.