Download presentation
Presentation is loading. Please wait.
Published byAlexandra Natalie Wilcox Modified over 9 years ago
1
chapter 111© copyright Janson Industries 2011 Custom Tags ▮ Tag Handlers ▮ XML ▮ Tag Libraries ▮ Web Deployment Descriptor
2
chapter 112© copyright Janson Industries 2011 Why Custom Tags? ▮ Bean tags are limited: useBean, getProperty, and setProperty ▮ Often need functions in JSPs that require scripts or extensive JSTL tags ▮ Using custom tags instead: ▮ Simplifies the coding in the JSPs ▮ Makes functions accessible to all JSPs ▮ Easier to change the function
3
chapter 113© copyright Janson Industries 2011 How do tags work? ▮ Tags can be tied to a java class called a tag handler ▮ As the tag is read, various tag handler methods will be invoked (by the server) ▮ doStartTag ▮ doInitBody ▮ doAfterBody ▮ doEndTag ▮ release
4
chapter 114© copyright Janson Industries 2011 Generic Tag Classes ▮ A class is defined as a tag handler by extending a generic tag class or implementing a tag interface ▮ By implementing an interface or extending a generic tag class, the tag handler gets useful methods and variables
5
chapter 115© copyright Janson Industries 2011 ▮ Generic tag classes ▮ TagSupport ▮ BodyTagSupport (extends TagSupport) ▮ Tag interfaces ▮ Tag ▮ IterationTag (extends Tag) ▮ BodyTag (extends IterationTag) Generic Tag Classes
6
chapter 116© copyright Janson Industries 2011 Generic Tag Classes ▮ TagSupport (implements IterationTag) subclasses inherit the methods: ▮ doStartTag ▮ doAfterBody ▮ doEndTag ▮ release ▮ BodyTagSupport (extends TagSupport and implements BodyTag) subclasses inherit the additional method: ▮ doInitBody
7
chapter 117© copyright Janson Industries 2011
8
chapter 118© copyright Janson Industries 2011 Creating a tag handler ▮ Generates the following code: ▮ Not too exciting ▮ Need to add tag methods package c11; import javax.servlet.jsp.tagext.BodyTagSupport; public class TestTag extends BodyTagSupport { }
9
chapter 119© copyright Janson Industries 2011 Click Source, Override/Implement Methods, select these methods, then click OK
10
chapter 1110© copyright Janson Industries 2011 New methods simply call the superclass’ overridden methods
11
chapter 1111© copyright Janson Industries 2011 We will add this code to the doStartTag method A tag handler has been defined...
12
chapter 1112© copyright Janson Industries 2011 ▮..however, creating a tag, tying a tag to a tag handler, and using the tag is a little more complicated ▮ A tag is defined and associated with a tag handler class in a tag library ▮ A tag library is a TLD (Tag Library Description) file that contains XML to associate tag(s) and tag handler(s) class(es) Creating a Tag
13
chapter 1113© copyright Janson Industries 2011 ▮ We will create a folder to hold tag libraries in MyWeb called TagLibs ▮ Within TagLibs we will create a tld file called MyTagLib ▮ Within MyTagLib, we will define a tag called mFT (MyFirstTag) and associate it with TestTag Creating a Tag Library
14
chapter 1114© copyright Janson Industries 2011 Tag Libraries must reside in Web-INF
15
chapter 1115© copyright Janson Industries 2011 Create a new file in TagLibs
16
chapter 1116© copyright Janson Industries 2011
17
chapter 1117© copyright Janson Industries 2011 Just need to add the XML to tie the tag to the tag handler
18
chapter 1118© copyright Janson Industries 2011 XML ▮ eXtensible Markup Language ▮ The "Duct Tape" of the Internet ▮ XML similar in syntax to all MLs ▮ Start Tags ▮ End Tags ▮ To define a tag, use the tag, name, and tagclass tags
19
chapter 1119© copyright Janson Industries 2011 mFT c11.TestTag XML ▮ XML syntax very flexible. This works too: mFT c11.TestTag
20
chapter 1120© copyright Janson Industries 2011 Using a Tag ▮ A little more complicated ▮ Simply coding the tag in a JSP is easy ▮ However, must tell the server where the tag library is ▮ So the server can find/run the tag handler ▮ A taglib directive (in the JSP) tells the server where to find the tag library with a URI (uniform resource identifier)
21
chapter 1121© copyright Janson Industries 2011 For instance, when a forEach tag was inserted from the palette..
22
chapter 1122© copyright Janson Industries 2011...RAD inserted the tag (notice the prefix c)...
23
chapter 1123© copyright Janson Industries 2011... as well as taglib directives The taglib directive indicates the URI for the correct taglib
24
chapter 1124© copyright Janson Industries 2011 taglib directive ▮ Multiple tag libraries can be accessed in a JSP ▮ Therefore, taglib directives must assign a prefix (nickname) for each taglib ▮ And when the custom tag is specified, the prefix must be included
25
chapter 1125© copyright Janson Industries 2011 URI ▮ Lastly, the URI is tied to an actual path/file (in the Web deployment descriptor) ▮ For this example, we will create: ▮ A Tag Lib Reference in the Web deployment descriptor that ties MyTagLib.tld to the URI http://www.mytags.com/ http://www.mytags.com/ ▮ TT.jsp (TagTest). In TT: ▮ A taglib directive for the URI and prefix ▮ The mFT tag with a prefix
26
chapter 1126© copyright Janson Industries 2011 Quick Review URI: http://www.mytags.com/ Location: /WEB-INF/TagLibs/MyTagLib.tld Tag prefix identifies correct taglib directive Taglib directive tells server to go to deployment descriptor Deployment descriptor identifies the correct tag library mFT c11.TestTag Tag definition identifies tag handler class to run
27
chapter 1127© copyright Janson Industries 2011 Why define a URI? ▮ You could specify the taglib file in the taglib directive ▮ However, if file location or name changes, all JSPs that use the tag library must be updated ▮ If URI defined in deployment descriptor: ▮ A change in the taglib location or name means only updating the tag library reference in the Web deployment descriptor
28
chapter 1128© copyright Janson Industries 2011 TT has some static text
29
chapter 1129© copyright Janson Industries 2011 RAD not happy with taglib directive because the URI isn’t in the deployment descriptor In fact, there is no deployment descriptor! We insert the taglib directive and tag in the source code
30
chapter 1130© copyright Janson Industries 2011 To create a deployment descriptor, right click the project and select Java EE and Generate Deployment Descriptor Stub
31
chapter 1131© copyright Janson Industries 2011 A file called web.xml is created in WEB-INF Open by right clicking, select Open With, then Web Application 3.0 Deployment Descriptor Editor
32
chapter 1132© copyright Janson Industries 2011 Click Add… …from Add Item, select JSP Configuration and then click OK
33
chapter 1133© copyright Janson Industries 2011 Click Add again … …select Taglib and then click OK
34
chapter 1134© copyright Janson Industries 2011 Specify the tag library file and the URI
35
chapter 1135© copyright Janson Industries 2011 Save the deployment descriptor. Reference added.
36
chapter 1136© copyright Janson Industries 2011 When MyTagLib file created, didn’t specify the file extension as.tld
37
chapter 1137© copyright Janson Industries 2011 Rename and add.tld
38
chapter 1138© copyright Janson Industries 2011 Run TT.jsp on server
39
chapter 1139© copyright Janson Industries 2011 Custom Tag ▮ In the future defining a tag will be faster because you won't have to: ▮ Create a tag library and deployment descriptor ▮ Define a URI in the deployment descriptor ▮ You still have to: ▮ Define a tag handler ▮ Use XML to define the tag in the tag library
40
chapter 1140© copyright Janson Industries 2011 Tag Handler ▮ Tag handler methods are executed in a particular order ▮ For instance, doEndTag executed after doStartTag ▮ However, which tag handler methods are executed is based on whether the tag body is empty and what doStartTag returns ▮ Let's prove...
41
chapter 1141© copyright Janson Industries 2011
42
chapter 1142© copyright Janson Industries 2011 Refresh the browser
43
chapter 1143© copyright Janson Industries 2011 Tag Handler ▮ Notice, not all tag handler methods were run ▮ This is because (by default) doStartTag returns the inherited value SKIP_BODY ▮ If we: ▮ Put text in the tag body ▮ Change the returned value to EVAL_BODY_INCLUDE
44
chapter 1144© copyright Janson Industries 2011 Put some text in the tag body
45
chapter 1145© copyright Janson Industries 2011 Change doStartTag to return EVAL_BODY_INCLUDE
46
chapter 1146© copyright Janson Industries 2011 Tag body content (hello) passed to the JSP Writer (and displayed) and doAfterBody run
47
chapter 1147© copyright Janson Industries 2011 Change doStartTag to EVAL_BODY_BUFFERED
48
chapter 1148© copyright Janson Industries 2011 Content not passed to JSP writer and no other methods called However body content is available in a server supplied BodyContent object called bodyContent
49
chapter 1149© copyright Janson Industries 2011 To retrieve body text use bodyContent.getString()
50
chapter 1150© copyright Janson Industries 2011 When body content is accessed: 1. doInitBody run 2. content is returned (and displayed) 3. doAfterBody run Then doEndTag finishes (skips a line) and release is invoked
51
chapter 1151© copyright Janson Industries 2011 Can prove that doInitBody and doAfterBody are called by bodyContent.getString() After bodyContent.getString(), printed a tag Notice that it is printed after the doAfterBody msg then the release method invoked
52
chapter 1152© copyright Janson Industries 2011 Tag Attributes ▮ Even though the tag handler has full access to the body content... ▮...body content not the way to control tag functions or pass info to tag ▮ Tag attributes used to specify tag parameters
53
chapter 1153© copyright Janson Industries 2011 Test Tag ▮ Change the tag so that the tag body content can be turned into a hyperlink email addr ▮ With option to specify the email addr ▮ Two tag attributes: ▮ One to specify whether to change to link ▮ One to specify the email addr
54
chapter 1154© copyright Janson Industries 2011 link true addr Tag Attributes ▮ Defined with XML in the tag definition ▮ An attribute defined as required true, must be specified in the tag
55
chapter 1155© copyright Janson Industries 2011 Current Tag Definition
56
chapter 1156© copyright Janson Industries 2011 Tag Attributes ▮ For each attribute, must have a private String of the same name in the tag handler ▮ Tag handler needs setters and getters for each attribute variable ▮ If the attribute is specified in the tag, server will invoke setter in tag handler ▮ Tag handler must check variable to see if function should be performed
57
chapter 1157© copyright Janson Industries 2011 private String link; private String addr; public String getLink() { return link; } public void setLink(String l) { link = l;} public String getAddr() { return addr;} public void setAddr(String a) { addr = a;} Tag Attributes
58
chapter 1158© copyright Janson Industries 2011 Link Attribute ▮ When Link is “t”, tag body text must be defined as an email link ▮ If an addr parameter is specified that email addr is used else a default address of wsjavaws@kaxy.com will be used ▮ This is HTML to define an email link
59
chapter 1159© copyright Janson Industries 2011 if (link.equals("t")){ pageContext.getOut().write("<A href=\"mailto:"); if (addr == null){ pageContext.getOut().write("wsjavaws@kaxy.com\">"); } else{ pageContext.getOut().write(addr + "\">"); } } doEndTag ▮ \" forces a " to be written onto page ▮ Will comment out the text printouts in all the methods
60
chapter 1160© copyright Janson Industries 2011 New tag handler code Commented out text printouts
61
chapter 1161© copyright Janson Industries 2011 Must specify the required attribute link
62
62 Move mouse over link to show mail to address
63
chapter 1163© copyright Janson Industries 2011 This time specify a address
64
chapter 1164© copyright Janson Industries 2011 Save TT, refresh browser, move mouse over link to show new "mail to" address
65
chapter 1165© copyright Janson Industries 2011 Business Change ▮ Want to be able to insert and pay POs online ▮ Create a Web based application (using custom tags) to do this ▮ Easier to do this because of MVC ▮ Because Model classes are separate from the View (i.e. Frame) classes, can easily incorporate Client App Model into Web App
66
chapter 1166© copyright Janson Industries 2011 Business Change ▮ Need to insert PO info on the Web ▮ Could create a static Web page requiring user to input all the PO info ▮ That would be a lot of repetitive work for the user ▮ Must enter Customer name, item, date for each PO
67
chapter 1167© copyright Janson Industries 2011 Inserting a PO ▮ Instead, display all schools (in a DDM using a custom tag) and if the school name exists, populate the JSP with ▮ Customer name ▮ Current date ▮ Last purchase info ▮ Must provide for a new school also
68
chapter 1168© copyright Janson Industries 2011 So when user starts the “create PO process” we display a dropdown menu with existing schools And if they select an already existing school like Death Valley Univ...
69
chapter 1169© copyright Janson Industries 2011 The school name, buyer and previous purchase info is displayed Also set the purchase date to the current date and have a button to actually insert the PO
70
chapter 1170© copyright Janson Industries 2011 And if they specify a new school...
71
chapter 1171© copyright Janson Industries 2011...we can at least set the purchase date
72
Chapter 8 72 © copyright Janson Industries 2011 Inserting a PO View InsertPO School.jsp User Sales DB All POs Model TransTable (POBean) SchoolTag Handler DDM with Schools
73
chapter 1173© copyright Janson Industries 2011 Inserting a PO ▮ Notice that TransTable is used in the Web-base app ▮ Because we did not embed the business logic/Model (TransTable) in a Frame class, it can be used on the Web ▮ Imagine if you had embedded it: ▮ You'd have to recode it for the Web ▮ Every change would be done twice, once for client app and once for Web app!!!
74
chapter 1174© copyright Janson Industries 2011 Inserting a PO ▮ Need to copy TransTable class into MyWeb/Java Resources/src/c11 and ▮ DBFile ▮ AccessFile or DB2File or OracleFile ▮ InvalidLengthException ▮ These are the classes that comprise the client apps Model
75
Chapter 8 75© copyright Janson Industries 2011 After Specifying School Inserting ViewController School & purch info InsertPO School.jsp User ProcessPO School (servlet) Sales DB AddPO.jsp Redirects School & purch info & PO # Model PO # TransTable (POBean) All PO info Creates School
76
chapter 1176© copyright Janson Industries 2011 Inserting a PO ▮ TransTable needs a new business function (getSchoolInfo) that ▮ Reads TxTable for a particular school ▮ Populates the TransTable fields associated with that school and the last PO ▮ This is how new business functions for classes come about – changes in business
77
chapter 1177© copyright Janson Industries 2011 public void getSchoolInfo(String school) { read(" WHERE School = '" + school + "'"); this.getSchoolDataFromRS(); } private void getSchoolDataFromRS() { try { school = rs.getString(1); customer = rs.getString(2); itemName = rs.getString(5); qty = rs.getInt(4); price = rs.getDouble(6); } catch (SQLException sqlex) { sqlex.printStackTrace(); System.out.println("\nSQL exception on rs get\n"); } New TransTable Methods
78
chapter 1178© copyright Janson Industries 2011...and tie InsertPOSchool's form to the servlet ProcessPOSchool Insert custom tag (schoolsDDM) to display schools
79
chapter 1179© copyright Janson Industries 2011 schoolsDDM Tag ▮ Invokes SchoolTagHandler ▮ SchoolTagHandler will ▮ Create a TransTable object ▮ Invoke getAllPOs ▮ Generates the HTML that defines a DDM with the schools names
80
chapter 1180© copyright Janson Industries 2011 package c11; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class SchoolTagHandler extends TagSupport { TransTable tt = new TransTable(); ResultSet allPOsRS; String schools; public int doStartTag() throws JspException { try { pageContext.getOut().write(" "); allPOsRS = tt.getAllPOs(); schools = allPOsRS.getString(1); pageContext.getOut().write( " " + schools + " "); while (allPOsRS.next()) { schools = allPOsRS.getString(1); pageContext.getOut().write("<option selected value=\"" + schools + "\">" + schools + " ");} pageContext.getOut().write(" "); } catch (IOException e1) {e1.printStackTrace(); } catch (SQLException e) {e.printStackTrace();} return super.doStartTag(); } }
81
chapter 1181© copyright Janson Industries 2011 Add XML to MyTagLib that defines schoolsDDM and ties it to c11.SchoolTagHandler
82
chapter 1182© copyright Janson Industries 2011 ? is now resolved As an alternative to typing in the taglib directive and tag…
83
chapter 1183© copyright Janson Industries 2011 …click on Custom, then the location on the JSP to put the tag Need to specify the URI, click Add
84
chapter 1184© copyright Janson Industries 2011 Scroll down list and click www.mytags.com checkbox Must also specify a prefix
85
chapter 1185© copyright Janson Industries 2011 Select the tag, click Insert, then Close
86
chapter 1186© copyright Janson Industries 2011 Run to test
87
chapter 1187© copyright Janson Industries 2011 Inserting a PO ▮ New to add a button (when clicked, ProcessPOSchool, a servlet, is invoked) ▮ ProcessPOSchool ▮ Creates a TransTable object ▮ Defines it as a bean (POBean) ▮ If user entered a new school, sets bean school property to new school ▮ If not, invokes getSchoolInfo (passing the selected school) ▮ Redirects to AddPO.jsp
88
chapter 1188© copyright Janson Industries 2011 AddPO ▮ Retrieves data (from POBean) and displays: ▮ School info ▮ Last purchase info ▮ Purchase date
89
chapter 1189© copyright Janson Industries 2011 So if user chose Hard Knocks U… … last PO’s info displayed
90
chapter 1190© copyright Janson Industries 2011 <%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> AddPO Please enter the Purchase Order Information School: <input type="text" name="schoolTF" size="25" value="${POBean.school}"> Will invoke itself when button clicked Uses EL to retrieve info from POBean
91
chapter 1191© copyright Janson Industries 2011 Customer: <input type="text" name="custTF" size="30" value="${POBean.customer}"> Purchase Date: <input type="text" name="purchDataTF" size="10" value="${POBean.purchDate}"> Item: <input type="text" name="itemTF" size="30" value="${POBean.itemName}"> Quantity: <input type="text" name="qtyTF" size="5" value="${POBean.qty}"> Price: <input type="text" name="priceTF" size="7" value="${POBean.price}"> PO Number: Comments: <input type="text" name="commentsTF" size="30" maxlength="100"> <input type="submit" name="SubmitBtn" value="Add PO"> Gets rest of data from POBean and puts into textfields
92
chapter 1192© copyright Janson Industries 2011 AddPO ▮ When button clicked want to: ▮ Move data from text fields to PO Bean ▮ Write the PO to the DB
93
chapter 1193© copyright Janson Industries 2011 There is no setPurchDate that accepts a string
94
chapter 1194© copyright Janson Industries 2011 Need to create one
95
chapter 1195© copyright Janson Industries 2011 insertPO Tag ▮ Need another tag (insertPO) to invoke the write method ▮ Create InsertPOHandler ▮ Add XML to tag library ▮ Put tag in AddPO.jsp
96
chapter 1196© copyright Janson Industries 2011 package c11; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; public class InsertPOHandler extends TagSupport { TransTable tt; public int doStartTag() throws JspException { tt = (TransTable)pageContext.getSession().getAttribute("POBean"); tt.write(); return super.doStartTag(); } Retrieves POBean and invokes the write method
97
chapter 1197© copyright Janson Industries 2011 Add the XML to MyTagLib
98
chapter 1198© copyright Janson Industries 2011 In AddPO, insert the custom tag at the end of the if tag and add the page directive…
99
chapter 1199© copyright Janson Industries 2011 and define the prefix
100
chapter 11100© copyright Janson Industries 2011 Add the tag
101
chapter 11101© copyright Janson Industries 2011
102
chapter 11102© copyright Janson Industries 2011 Add a submit button to InsertPOSchool Must create ProcessPOSchool servlet
103
chapter 11103© copyright Janson Industries 2011 package c11; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/ProcessPOSchool") public class ProcessPOSchool extends HttpServlet { private static final long serialVersionUID = 1L; private String school = null; private TransTable newPO; public ProcessPOSchool() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
104
chapter 11104© copyright Janson Industries 2011 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { newPO = new TransTable(); newPO.setPurchDate(); school = request.getParameter("schoolTF"); if (school.equals("")){ school = request.getParameter("School"); newPO.getSchoolInfo(school); }else{ try { newPO.setSchool(school); } catch (InvalidLengthException e) { e.printStackTrace(); } HttpSession session = request.getSession(); session.setAttribute("POBean", newPO); response.sendRedirect("AddPO.jsp"); }
105
chapter 11105© copyright Janson Industries 2011 Run InsertPOSchool
106
chapter 11106© copyright Janson Industries 2011 Test by entering new school and click Submit
107
chapter 11107© copyright Janson Industries 2011
108
chapter 11108© copyright Janson Industries 2011 Add PO info and click AddPO
109
chapter 11109© copyright Janson Industries 2011 Prove it worked by going back to InsertPOSchool. New school will be in DDM.
110
chapter 11110© copyright Janson Industries 2011 Alternatives ▮ Custom tags can invoke JSP code instead of a TagHandler ▮ Need: ▮ A new folder called Tags in WEB-INF ▮ A tag file in tags folder with: ▮ the tag name as prefix ▮.tag as suffix ▮ Put JSP code in the tag file ▮ Insert taglib directive and tag in a JSP
111
chapter 11111© copyright Janson Industries 2011 Folder and file created, JSP code entered in tag file
112
chapter 11112© copyright Janson Industries 2011 Taglib directive ids prefix and location of the tag file Create JSP to use tag
113
chapter 11113© copyright Janson Industries 2011 Run UsingDudeJSP on server
114
chapter 11114© copyright Janson Industries 2011 Alternative ▮ Use this technique if JSP code will be used in many JSPs ▮ What actually happens is that the web container creates a tag handler from the JSP in the tag file ▮ Custom tag can receive attributes, pass variables back, & access all objects available to the JSP
115
chapter 11115© copyright Janson Industries 2011 Attributes ▮ To define, need an attribute directive in the tag file ▮ JSP using the tag specifies a value for attribute ▮ Tag file uses the attribute value
116
chapter 11116© copyright Janson Industries 2011 Dudecolor value accessed using EL then assigned to font's color attribute In tag file, attribute directive defines dudecolor
117
chapter 11117© copyright Janson Industries 2011 UsingDudeJSP sets a value for attribute dudecolor
118
chapter 11118© copyright Janson Industries 2011 Run UsingDudeJSP on server (may have to remove app from server to force reload of dude.tag, then refresh browser)
119
chapter 11119© copyright Janson Industries 2011 JSP creates request variable custname and sets value to John. (Also, need taglib directive to core) Changed color to green.
120
chapter 11120© copyright Janson Industries 2011 Tag gets the custname value using EL and displays
121
chapter 11121© copyright Janson Industries 2011 The tag accessed the variable
122
chapter 11122© copyright Janson Industries 2011 To access the body of a tag: Also, tag will display in brown to prove that tag retrieves and displays the content (not the JSP)
123
chapter 11123© copyright Janson Industries 2011 Content in the tag body (changed dudecolor too)
124
chapter 11124© copyright Janson Industries 2011
125
chapter 11125© copyright Janson Industries 2011 Can define a variable in the tag file with a variable directive (Must have taglib directive to core) Then use/access via tags and EL
126
chapter 11126© copyright Janson Industries 2011 May have to remove app from server to force reload of dude.tag, then refresh browser (or create a new server to run on)
127
chapter 11127© copyright Janson Industries 2011 Points to Remember ▮ Custom tags used to simplify JSP coding ▮ If custom tag tied to tag handler: ▮ Tag prefix identifies a taglib directive ▮ Taglib directive identifies the URI ▮ Deployment descriptor ties URI to tag library ▮ Tab library contains the tag definition ▮ Tag definition identifies tag handler to be run
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.