190 likes | 377 Views
JSP with Custom Tags. Blake Adams 2-19-2003. 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
E N D
JSP with Custom Tags Blake Adams 2-19-2003
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
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
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()
Example 1 – page counter Tag with no attributes • The JSP File <html><head><title>A Counter Page</title></head><body> <%@ taglib uri = ‘/WEB-INF/tlds/counter.tld’ prefix=‘util’ %> This page has been accessed <b><util:counter/></b> times. </body></html> - 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’
Example 1 – page counter • The TLD File <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>Sun Microsystems PressTag Library</shortname> <info>Example 1-2b from book – single counter tag</info> <tag> (definition identifier) <name>counter</name> <tagclass>tags.CounterTag</tagclass> //tag handler <bodycontent>empty</bodycontent> </tag> </taglib> - 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
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;
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
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(); } }
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()); } }
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
Example 1 – page counter • Indirectily specifying TLD in WEB-INF/web.xml file //in the JSP file… <%@ taglib uri=‘counters’ prefix=‘util’ %> //in web.xml … <taglib> <taglib-uri>counter<taglib-uri> <taglib-location>/WEB-INF/tlds/counter.tld</taglib-location> </taglib>
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 getAttrmethod 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.
Example 2 – RegistrationTag with attributes • The JSP File <html><head><title>Registration Page</title></head> <body> <%@ taglib uri='WEB-INF/tlds/html.tld' prefix='html'%> <h2>Please Register</h2><hr> <form action='<%= response.encodeURL("CentralServlet") %> 'method='post'> <table> <tr><td> First Name: </td> <td><input type='text' size=15 name='firstName' value='<html:requestParameter property="firstName"/>'> </td></tr> <tr><td> Last Name: </td> <td><input type='text' size=15 name='lastName' value='<html:requestParameter property="lastName"/>'> </td> </tr> <tr><td> E-mail Address: </td> <td><input type='text' size=25 name='emailAddress' value='<html:requestParameter property="emailAddress"/>'> </td></tr> </table> </p> <br> <input type='submit' value='register'> <input type='hidden' name='action' value='register-action'> </form></body></html>
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; }
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"); } }
Example 2 – Registration • The TLD File <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>Sun Microsystems Press Examples</shortname> <tag> <name>requestParameter</name> <tagclass>tags.GetRequestParameterTag</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>property</name>//name of attribute <required>true</required>//true, thus must be specified <rtexprvalue>true</rtexprvalue>//true, thus can be specified </attribute> //with a JSP request time attribute </tag> </taglib>
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; } }
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