320 likes | 830 Views
Internetteknologi 2 (ITNET2). J2EE Java Server Pages (JSP) Avanceret. Indhold i denne præsentation. Java Server Pages (JSP): Simpelt eksempel hvor vi gør brug af en database sammen med JSP Brug af custom tags samt JSTL Brug af Expression Language (EL). < jsp:useBean > Action.
E N D
Internetteknologi 2 (ITNET2) J2EE Java Server Pages (JSP) Avanceret
Indhold i denne præsentation • Java Server Pages (JSP): • Simpelt eksempel hvor vi gør brug af en database sammen med JSP • Brug af custom tags samt JSTL • Brug af Expression Language (EL)
<jsp:useBean> Action • Vi tager endnu et DEITEL eksempel • Eksemplet er en gæste bog (GuestBook) • Der benytter sig af en database til at gemme data • I kapitel 30 i DEITEL fik I et eksempl på hvordan en Servlet kunne tilgå en JDBC database – dette var et klassisk skolebogs eksempel • Dog bør man ikke tillade så tæt kobling i større Web Applikationer • Hos DEITEL eksemplet afkobles der derfor vha. to JavaBeans, en value-bean og en data-bean • Klassen GuestBean og klassen GuestDataBean
3 package com.deitel.advjhtp1.jsp.beans; 4 5 public class GuestBean { 6 private String firstName, lastName, email; 7 8 // set the guest's first name 9 public void setFirstName( String name ) 10 { 11 firstName = name; 12 } 13 15 public String getFirstName() 16 { 17 return firstName; 18 } 19 21 public void setLastName( String name ) 22 { 23 lastName = name; 24 } 25 27 public String getLastName() 28 { 29 return lastName; 30 } 31 33 public void setEmail( String address ) 34 { 35 email = address; } Guest-Bean.javaDefine Bean GuestBeanStorage Bean 39 public String getEmail() 40 { 41 return email; 42 } 43 }
Defines the database driver, URL, and SQL statements. 1 // Fig. 31.21: GuestDataBean.java 2 // Class GuestDataBean makes a database connection and supports 3 // inserting and retrieving data from the database. 4 package com.deitel.advjhtp1.jsp.beans; 5 6 // Java core packages 7 import java.io.*; 8 import java.sql.*; 9 import java.util.*; 10 11 public class GuestDataBean { 12 private Connection connection; 13 private PreparedStatement addRecord, getRecords; 14 15 // construct TitlesBean object 16 public GuestDataBean() throws Exception 17 { 18 // load the Cloudscape driver 19 Class.forName( "COM.cloudscape.core.RmiJdbcDriver" ); 20 21 // connect to the database 22 connection = DriverManager.getConnection( 23 "jdbc:rmi:jdbc:cloudscape:guestbook" ); 24 25 getRecords = 26 connection.prepareStatement( 27 "SELECT firstName, lastName, email FROM guests" 28 ); 29 30 addRecord = 31 connection.prepareStatement( 32 "INSERT INTO guests ( " + 33 "firstName, lastName, email ) " + 34 "VALUES ( ?, ?, ? )" 35 ); Guest-DataBean.javaDefine Class GuestDataBeanSet up database
Obtain the guest list from the database. Return each guest in a bean. 36 } 37 38 // return an ArrayList of GuestBeans 39 public List getGuestList() throws SQLException 40 { 41 List guestList = new ArrayList(); 42 43 // obtain list of titles 44 ResultSet results = getRecords.executeQuery(); 45 46 // get row data 47 while ( results.next() ) { 48 GuestBean guest = new GuestBean(); 49 50 guest.setFirstName( results.getString( 1 ) ); 51 guest.setLastName( results.getString( 2 ) ); 52 guest.setEmail( results.getString( 3 ) ); 53 54 guestList.add( guest ); 55 } 56 57 return guestList; 58 } 59 60 // insert a guest in guestbook database 61 public void addGuest( GuestBean guest ) throws SQLException 62 { 63 addRecord.setString( 1, guest.getFirstName() ); 64 addRecord.setString( 2, guest.getLastName() ); 65 addRecord.setString( 3, guest.getEmail() ); 66 67 addRecord.executeUpdate(); 68 } 69 70 // close statements and terminate database connection Guest-DataBean.javaDatabase access methods
71 protected void finalize() 72 { 73 // attempt to close database connection 74 try { 75 getRecords.close(); 76 addRecord.close(); 77 connection.close(); 78 } 79 80 // process SQLException on close operation 81 catch ( SQLException sqlException ) { 82 sqlException.printStackTrace(); 83 } 84 } 85 } Guest-DataBean.javaClose database
Obtain an instance of each bean. Assigns the bean name within the JSP. 1 <?xml version ="1.0"?> 2 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 31.22: guestBookLogin.jsp --> 6 7 <%-- page settings --%> 8 <%@page errorPage ="guestBookErrorPage.jsp" %> 9 10 <%-- beans used in this JSP --%> 11 <jsp:useBean id ="guest" scope = "page" 12 class = "com.deitel.advjhtp1.jsp.beans.GuestBean" /> 13 <jsp:useBean id ="guestData" scope ="request" 14 class ="com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> 15 16 <html xmlns ="http://www.w3.org/1999/xhtml"> 17 18 <head> 19 <title>Guest Book Login</title> 20 21 <style type ="text/css"> 22 body { 23 font-family: tahoma, helvetica, arial, sans-serif; 24 } 25 26 table, tr, td { 27 font-size: .9em; 28 border: 3px groove; 29 padding: 5px; 30 background-color: #dddddd; 31 } 32 </style> 33 </head> 34 35 <body> GuestBook-Login.jspuseBean action
36 <jsp:setProperty name ="guest"property = "*" /> 37 38 <% // start scriptlet 39 40 if ( guest.getFirstName() == null || 41 guest.getLastName() == null || 42 guest.getEmail() == null ) { 43 44 %><%-- end scriptlet to insert fixed template data --%> 45 46 <form method ="post"action ="guestBookLogin.jsp"> 47 <p>Enter your first name, last name and email 48 address to register in our guest book.</p> 49 50 <table> 51 <tr> 52 <td>First name</td> 53 54 <td> 55 <input type ="text" name ="firstName"/> 56 </td> 57 </tr> 58 59 <tr> 60 <td>Last name</td> 61 62 <td> 63 <input type = "text"name = "lastName"/> 64 </td> 65 </tr> 66 67 <tr> 68 <td>Email</td> 69 70 <td> Use <setProperty> to extract the parameters from the request – and save them in the “guest” bean GuestBook-Login.jspObtain information from user Check for data
Calls the guestData Bean to write this new guest into the address book. Then forward the client to the guestBookView JSP. 71 <input type ="text"name ="email" /> 72 </td> 73 </tr> 74 75 <tr> 76 <td colspan ="2"> 77 <input type ="submit" 78 value = "Submit"/> 79 </td> 80 </tr> 81 </table> 82 </form> 83 84 <% // continue scriptlet 85 86 } // end if 87 else { 88 guestData.addGuest( guest ); 89 90 %><%-- end scriptlet to insert jsp:forward action --%> 91 92 <%-- forward to display guest book contents --%> 93 <jsp:forward page ="guestBookView.jsp"/> 94 95 <% // continue scriptlet 96 97 } // end else 98 99 %><%-- end scriptlet --%> 100 </body> 101 102 </html> GuestBook-Login.jspAdd new guest to book
Obtain an instance of the GuestDataBean class with useBean action. 1 <?xml version ="1.0"?> 2 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 31.23: guestBookView.jsp --> 6 7 <%-- page settings --%> 8 <%@ page errorPage ="guestBookErrorPage.jsp" %> 9 <%@ page import ="java.util.*"%> 10 <%@page import ="com.deitel.advjhtp1.jsp.beans.*" %> 11 12 <%-- GuestDataBean to obtain guest list --%> 13 <jsp:useBean id ="guestData"scope = "request" 14 class ="com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> 15 16 <html xmlns ="http://www.w3.org/1999/xhtml"> 17 18 <head> 19 <title>Guest List</title> 20 21 <style type = "text/css"> 22 body { 23 font-family: tahoma, helvetica, arial, sans-serif; 24 } 25 26 table, tr, td, th { 27 text-align: center; 28 font-size: .9em; 29 border: 3px groove; 30 padding: 5px; 31 background-color: #dddddd; 32 } 33 </style> 34 </head> 35 GuestBook-View.jsp
Obtain, then Iterate through the guestList and display its contents. 36 <body> 37 <p style ="font-size: 2em;">Guest List</p> 38 39 <table> 40 <thead> 41 <tr> 42 <th style ="width: 100px;">Last name</th> 43 <th style ="width: 100px;">First name</th> 44 <th style ="width: 200px;">Email</th> 45 </tr> 46 </thead> 47 48 <tbody> 49 50 <%// start scriptlet 51 52 List guestList = guestData.getGuestList(); 53 Iterator guestListIterator = guestList.iterator(); 54 GuestBean guest; 55 56 while ( guestListIterator.hasNext() ) { 57 guest = ( GuestBean ) guestListIterator.next(); 58 59 %><%-- end scriptlet; insert fixed template data --%> 60 61 <tr> 62 <td><%= guest.getLastName() %></td> 63 64 <td><%= guest.getFirstName() %></td> 65 66 <td> 67 <a href ="mailto:<%= guest.getEmail() %>"> 68 <%= guest.getEmail() %></a> 69 </td> 70 </tr> GuestBook-View.jsp
71 72 <%// continue scriptlet 73 74 } // end while 75 76 %><%-- end scriptlet --%> 77 78 </tbody> 79 </table> 80 </body> 81 82 </html> GuestBook-View.jsp
1 <?xml version ="1.0"?> 2 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 31.24: guestBookErrorPage.jsp --> 6 7 <%-- page settings --%> 8 <%@pageisErrorPage = "true" %> 9 <%@pageimport = "java.util.*"%> 10 <%@pageimport ="java.sql.*"%> 11 12 <html xmlns ="http://www.w3.org/1999/xhtml"> 13 14 <head> 15 <title>Error!</title> 16 17 <style type = "text/css"> 18 .bigRed { 19 font-size: 2em; 20 color: red; 21 font-weight: bold; 22 } 23 </style> 24 </head> 25 26 <body> 27 <p class ="bigRed"> 28 29 <% // scriptlet to determine exception type 30 // and output beginning of error message 31 if ( exception instanceof SQLException ) 32 %> 33 34 An SQLException 35 GuestBook-ErrorPage.jspError page
36 <% 37 else if ( exception instanceof ClassNotFoundException ) 38 %> 39 40 A ClassNotFoundException 41 42 <% 43 else 44 %> 45 46 An exception 47 48 <%-- end scriptlet to insert fixed template data --%> 49 50 <%-- continue error message output --%> 51 occurred while interacting with the guestbook database. 52 </p> 53 54 <p class = "bigRed"> 55 The error message was:<br /> 56 <%= exception.getMessage() %> 57 </p> 58 59 <p class ="bigRed">Please try again later</p> 60 </body> 61 62 </html> GuestBook-ErrorPage.jsp
Custom Tag Libraries • Indkaplser kompleks JSP funktionalitet i et skræddersyet tag • Scriptlets kan være svære at forstå for HTML udviklere • Defineret i Tag i pakken javax.servlet.jsp.tagtext • Extender normalt TagSupport eller BodyTagSupport • Tillader udviklere at udvikle JSP sider uden Java viden • Kan manipulere JSP sider direkte • Der kan købes tag libraries • Jeg har blandede følelser – der er pro et contra her … • JSPs tilgang via taglib direktivet • DEITEL tabel viser sammenhængene
Eksempel fra DEITEL • Der skal laves en klasse der extender TagSupport klassen • Her kan der laves ny funktionalitet • Der skal laves et XML dokument (.tld) der kaldes en tag library descriptor file. • Ligesom ved Servlets kobler dette dokument til én eller flere klasser der extender TagSupport • Herefter skal der blot bruges direktivet: • <%@taglib uri ="advjhtp1-taglib.tld"prefix = "advjhtp1"%> • Der så kan bruge: • <advjhtp1:welcome />
Specify the location of the tag library with the taglib directive. Call custom tag. 1 <?xml version ="1.0"?> 2 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 31.30: customTagWelcome.jsp --> 6 <!-- JSP that uses a custom tag to output content. --> 7 8 <%-- taglib directive --%> 9 <%@taglib uri ="advjhtp1-taglib.tld"prefix = "advjhtp1"%> 10 11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 13 <head> 14 <title>Simple Custom Tag Example</title> 15 </head> 16 17 <body> 18 <p>The following text demonstrates a custom tag:</p> 19 <h1> 20 <advjhtp1:welcome /> 21 </h1> 22 </body> 23 24 </html> CustomTagWelcome.jspCustom tag exampleProgram Output
Load tag and print welcome. 1 // Fig. 31.31: WelcomeTagHandler.java 2 // Custom tag handler that handles a simple tag. 3 package com.deitel.advjhtp1.jsp.taglibrary; 4 5 // Java core packages 6 import java.io.*; 7 8 // Java extension packages 9 import javax.servlet.jsp.*; 10 import javax.servlet.jsp.tagext.*; 11 12 public class WelcomeTagHandler extends TagSupport { 13 14 // Method called to begin tag processing 15 public int doStartTag() throws JspException 16 { 17 // attempt tag processing 18 try { 19 // obtain JspWriter to output content 20 JspWriter out = pageContext.getOut(); 21 22 // output content 23 out.print( "Welcome to JSP Tag Libraries!" ); 24 } 25 26 // rethrow IOException to JSP container as JspException 27 catch( IOException ioException ) { 28 throw new JspException( ioException.getMessage() ); 29 } 30 31 returnSKIP_BODY; // ignore the tag's body 32 } 33 } WelcomeTagHandler.javaDefine tag handler WelcomeTagHandler Implements custom tag functionality
Required taglibrary meta information Designate the tags name and location, and that this tag has no attributes. 1 <?xml version ="1.0"encoding = "ISO-8859-1"?> 2 <!DOCTYPE taglib PUBLIC 3 "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" 4 "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 5 6 <!-- a tag library descriptor --> 7 8 <taglib> 9 <tlibversion>1.0</tlibversion> 10 <jspversion>1.1</jspversion> 11 <shortname>advjhtp1</shortname> 12 13 <info> 14 A simple tab library for the examples 15 </info> 16 17 <!-- A simple tag that outputs content --> 18 <tag> 19 <name>welcome</name> 20 21 <tagclass> 22 com.deitel.advjhtp1.jsp.taglibrary.WelcomeTagHandler 23 </tagclass> 24 25 <bodycontent>empty</bodycontent> 26 27 <info> 28 Inserts content welcoming user to tag libraries 29 </info> 30 </tag> 31 </taglib> advjhtp1-taglib.tldDefine tag information Custom tag library descriptor file (advjhtp1-taglib.tld).
Custom Tag med attributter • Mulighed for at sende data med • I følgende eksempel gennemgås dette detaljeret • N.B. dette gennemgås kun kursorisk – det er ikke pensum
Include the custom tag library. Specifying an attribute for a custom tag. 1 <?xml version ="1.0"?> 2 <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 31.33: customTagAttribute.jsp --> 6 <!-- JSP that uses a custom tag to output content. --> 7 8 <%-- taglib directive --%> 9 <%@taglib uri ="advjhtp1-taglib.tld" prefix ="advjhtp1"%> 10 11 <html xmlns = "http://www.w3.org/1999/xhtml"> 12 13 <head> 14 <title>Specifying Custom Tag Attributes</title> 15 </head> 16 17 <body> 18 <p>Demonstrating an attribute with a string value</p> 19 <h1> 20 <advjhtp1:welcome2firstName = "Paul"/> 21 </h1> 22 23 <p>Demonstrating an attribute with an expression value</p> 24 <h1> 25 <%-- scriptlet to obtain "name" request parameter --%> 26 <% 27 String name = request.getParameter( "name" ); 28 %> 29 30 <advjhtp1:welcome2 firstName = "<%= name %>"/> 31 </h1> 32 </body> 33 34 </html> CustomTagAttribute.jsp
3 package com.deitel.advjhtp1.jsp.taglibrary; 4 5 // Java core packages 6 import java.io.*; 7 8 // Java extension packages 9 import javax.servlet.jsp.*; 10 import javax.servlet.jsp.tagext.*; 11 12 public class Welcome2TagHandler extends TagSupport { 13 private String firstName = ""; 14 15 // Method called to begin tag processing 16 public int doStartTag() throws JspException 17 { 18 // attempt tag processing 19 try { 20 // obtain JspWriter to output content 21 JspWriter out = pageContext.getOut(); 22 23 // output content 24 out.print( "Hello " + firstName + 25 ", <br />Welcome to JSP Tag Libraries!" ); 26 } 27 28 // rethrow IOException to JSP container as JspException 29 catch( IOException ioException ) { 30 throw new JspException( ioException.getMessage() ); 31 } 33 returnSKIP_BODY; // ignore the tag's body 34 } Welcome2TagHandler.javaDefine Class Welcome2TagHandler.javaDisplays attribute value 37 public void setFirstName( String username ) 38 { 39 firstName = username; 40 } 41 }
Define attribute parameters 1 <!-- A tag with an attribute --> 2 <tag> 3 <name>welcome2</name> 4 5 <tagclass> 6 com.deitel.advjhtp1.jsp.taglibrary.Welcome2TagHandler 7 </tagclass> 8 9 <bodycontent>empty</bodycontent> 10 11 <info> 12 Inserts content welcoming user to tag libraries. Uses 13 attribute "name" to insert the user's name. 14 </info> 15 16 <attribute> 17 <name>firstName</name> 18 <required>true</required> 19 <rtexprvalue>true</rtexprvalue> 20 </attribute> 21 </tag> advjhtp1-taglib.tld Element tag for the welcome2 custom tag.
Expression Language (EL) • Fra Servlet 2.4 / JSP 2.0 specifikationerne • JSP 2.1 / JSF 1.0: Unified Expression Language • Simplificere data behandling med udtryk • Alternativ til at bruge scriplets / inline Java kode Immediate Evaluation Deferred Evaluation
EL Eksempel • En form med to tekstfelter udfylt af en ”customer” bean – og en submit funktion
JSTL • JavaServer Pages Standard Tag Library • Samling af tags (elementer) til brug i JSP • Alternativ til scriplets • Ovenstående erstatter for eksempel behovet for en scriplet med en løkke
JSP Documents • Traditionel JSP er HTML med indlejret kode • Overholder ikke XML wellformed syntaxen • Kan ikke editeres af en standard XML editor • JSP Documents • Alternativ til traditionel JSP • Ren XML syntax (wellformed) • Udviklet til brug for bl.a. JSF og IDE støttet udvikling • Vil formodentligt på sigt erstatte traditionel syntax
JSP Document XML Syntax Samme Dokument! Mere Elegant