980 likes | 1.24k Views
Chapter 25. JavaServer Pages and Servlets. CHAPTER GOALS. To implement dynamic web pages with JavaServer Pages technology To learn the syntactical elements of JavaServer Pages To structure a web application as a sequence of JavaServer Pages
E N D
Chapter 25 JavaServer Pages and Servlets
CHAPTER GOALS • To implement dynamic web pages with JavaServer Pages technology • To learn the syntactical elements of JavaServer Pages • To structure a web application as a sequence of JavaServer Pages • To understand the relationship between JavaServer Pages and servlets
Dynamic Web Content • You can use JavaServer Pages (JSP) to implement dynamic web pages • To use JSP's you need a web server that is integrated with a JSP container • Apache Tomcat server is free
Dynamic Web Content • A JavaServer Pages (JSP) page contains HTML tags and Java instructions • The Java instructions are executed each time the page is served to the browser • An instruction to insert the current date and time into a web page <%= new java.util.Date() %>
File date.jsp 01: <html> 02: <head> 03: <title>Date JSP</title> 04: </head> 05: <body> 06: <h1>Date JSP</h1> 07: <p>The current time is: 08: <%= new java.util.Date() %> 09: </p> 10: </body> 11: </html> 12:
To Deploy the Date Page 1. Type the JSP file into a text editor 2. Place the file into a web application directory of your JSP engine 3. If you use Tomcat, create a subdirectory for the JSP file c:\jakarta-tomcat\webapps\bigjava 4. Place the date.jsp file into that directory 5. Start the web server 6. Point your browser to localhost:8080/bigjava/date.jsp
Dynamic Web Content • The JSP container reads the requested JSP page and transforms it into an HTML page • Regular HTML tags are left unchanged • JSP tags ( <%= . . . %> ) are processed • Expressions enclosed in JSP tags are evaluated and converted to a string using toString method
Dynamic Web Content • The string is inserted into the HTML page • The resulting document contains only HTML • The web server sends the document to the browser
Encapsulating Computations in JavaBeans • Most professional web pages need input from two different experts • A programmer who understands how to compute the results the page will display • A graphics designer who determines how to display the results • It is best to keep the Java code and the HTML tags separate • Any nontrivial computation should be carried out in a separate Java class • You connect one or more JavaBeans to a JSP page
Encapsulating Computations in JavaBeans • A JavaBean is a Java class • It must have a default constructor • A JavaBean exposes its properties through get and set methods • Properties are accessed and modified by methods that follow a naming convention
Encapsulating Computations in JavaBeans • If the property name is propertyName and the type is Type • accessor method • Type getPropertyName() • mutator method • void setpropertyName(Type newValue) • A boolean property uses a different convention • boolean isPropertyName() • void setPropertyName(boolean newValue) • By convention the name of the bean ends in Bean • Do not make any assumptions about the internal representation of the data
Encapsulating Computations in JavaBeans • A JSP page gives you access to a JavaBean's properties without having to write Java code. • To use a bean in a JSP page, use the jsp:useBean directive • Give a name to the object and specify the class name of the bean • <jsp:useBean id ="user" class="PersonBean"/> • This directive invokes the default constructor of the PersonBean class • It makes an object with name user
Encapsulating Computations in JavaBeans • To set a property in the bean, use the setProperty directive • <jsp:setProperty name="user" property="married" value="true"/> • To get a property in the bean, use the getProperty directive • <jsp:getProperty name="user" property="married"/> • This returns a string that becomes part of the HTML page
Encapsulating Computations in JavaBeans • We want to display just the current time, not the whole date • Get the time with the getTimeInstance method of the DateFormat class • Put this code in a bean class
01: import java.text.DateFormat; 02: import java.util.Date; 03: 04: /** 05: This bean formats the time of day from a given date. 06: */ 07: public class TimeFormatterBean 08: { 09: /** 10: Initializes the formatter. 11: */ 12: public TimeFormatterBean() 13: { 14: timeFormatter = DateFormat.getTimeInstance(); 15: } 16: 17: /** 18: Write-only date property. 19: @param aDate the date to be formatted. File TimeFormatterBean.Java
20: */ • 21: public void setDate(Date aDate) • 22: { • 23: theDate = aDate; • 24: } • 25: • 26: /** • 27: Read-only time property. • 28: @return the formatted time • 29: */ • 30: public String getTime() • 31: { • 32: String timeString = timeFormatter.format(theDate); • 33: return timeString; • 34: } • 35: • 36: private DateFormat timeFormatter; • 37: private Date theDate; • 38: }
01: <jsp:useBean id="formatter" class="TimeFormatterBean"/> 02: <jsp:setProperty name="formatter" property="date" value="<%= new java.util.Date() %>"/> 03: <html> 04: <head> 05: <title>Time JSP</title> 06: </head> 07: <body> 08: <h1>Time JSP</h1> 09: <p>The current time is: 10: <jsp:getProperty name="formatter" property="time"/> 11: </p> 12: </body> 13: </html> 14: File time.jsp
Encapsulating Computations in JavaBeans • It is a good idea to put the bean directive at the beginning of the JSP file, before the HTML • Both time.jsp and TimeFormatterBean must be deployed to the proper directories • time.jsp into • c:\Jakarta-tomcat\webapps\bigjava • TimeFormatterBean into • c:\Jakarta-tomcat\webapps\bigjava\WEB-INF\classes • You use JavaBeans to separate HTML presentation from Java computation
Handling Request Parameters • Modify the JSP page to take as input the user's city and to return the time in that time zone • The Java library contains a TimeZone class that knows about time zones • A time zone is identified by a string such as • "America/Los_Angeles" • "Asia/Tokyo" • The static method getAvailableIDs returns a string array containing all IDs • The static getTimeZone method returns a TimeZone class for a given ID string • String zoneID = "America/Los_Angeles"; • TimeZone zone = TimeZone.getTimeZone(zoneID);
Handling Request Parameters • The user will enter a city like Los Angeles • Our time zone bean will check whether that string appears at the end of one of the time zone ID's • The JSP page formats the current time in that time zone • Or prints a message that the city name is not found
Handling Request Parameters • We need an HTML form to get the user input • The form will have a textfield and a button to submit the form to the JSP
01: <html> 02: <head> 03: <title>Time Zone Form</title> 04: </head> 05: <body> 06: <form action="timezone.jsp"> 07: <p>City: 08: <input type="text" name="city"/> 09: <input type="submit" value="Get Time"/> 10: </p> 11: </form> 12: </body> 13: </html> File timezone.html
Handling Request Parameters • When a browser submits a form, it sends the names and values of all form elements to the web server • The name is city • the value is the contents of the text field • The action attribute of the form element specifies the URL of the server-side program that processes the form • In this case timezone.jsp • In a JSP page, you can access the form data through the predefined request object • The getParameter method of the ServletRequest class returns the value of the form element with a given name • To get the city that the user typed • <%= request.getParameter("city")%>
Handling Request Parameters • To set the city property in the TimeZoneBean <jsp:setProperty name="zone" property="city" value="<%= request.getParameter(\"city\")%> /> • A convenient shorthand • <jsp:setProperty name="zone" property="city" param="city"/>
01: <jsp:useBean id="zone" class="TimeZoneBean"/> 02: <jsp:setProperty name="zone" property="date" value="<%= new java.util.Date() %>"/> 03: <jsp:setProperty name="zone" property="city" param="city"/> <html> 04: <head> 05: <title>Time Zone JSP</title> 06: </head> 07: <body> 08: <h1>Time Zone JSP</h1> 09: <p>The current time in <%= request.getParameter("city") %> is: 10: <jsp:getProperty name="zone" property="time"/> 11: </p> 12: </body> 13: </html> File timezone.jsp
File TimeZoneBean.java 01: import java.text.DateFormat; 02: import java.util.Date; 03: import java.util.TimeZone; 04: 05: /** 06: This bean formats the local time of day for a given date 07: and city. 08: */ 09: public class TimeZoneBean 10: { 11: /** 12: Initializes the formatter. 13: */ 14: public TimeZoneBean() 15: { 16: timeFormatter = DateFormat.getTimeInstance(); 17: }
18: 19: /** 20: Write-only date property. 21: @param aDate the date to be formatted. 22: */ 23: public void setDate(Date aDate) 24: { 25: theDate = aDate; 26: } 27: 28: /** 29: Write-only city property. 30: @param aCity the city for which to report the local time 31: */ 32: public void setCity(String aCity) 33: { 34: city = aCity; 35: } 36: 37: /**
38: Read-only available property. 39: @return true if time zone information is available for 40: this city. 41: */ 42: public boolean isAvailable() 43: { 44: return getTimeZone(city) != null; 45: } 46: 47: /** 48: Read-only time property. 49: @return the formatted time 50: */ 51: public String getTime() 52: { 53: TimeZone zone = getTimeZone(city); 54: if (zone == null) return "not available"; 55: timeFormatter.setTimeZone(zone); 56: String timeString = timeFormatter.format(theDate); 57: return timeString;
58: } 59: 60: /** 61: Looks up the time zone for a city 62: @param aCity the city for which to find the time zone 63: @return the time zone or null if no match is found 64: */ 65: private static TimeZone getTimeZone(String city) 66: { 67: String[] ids = TimeZone.getAvailableIDs(); 68: for (int i = 0; i < ids.length; i++) 69: if (timeZoneIDmatch(ids[i], city)) 70: return TimeZone.getTimeZone(ids[i]); 71: return null; 72: } 73: 74: /** 75: Checks whether a time zone ID matches a city 76: @param id the time zone ID (e.g. "America/Los_Angeles") 77: @param aCity the city to match (e.g. "Los Angeles")
78: @return true if the ID and city match 79: */ 80: private static boolean timeZoneIDmatch(String id, String city) 81: { 82: String idCity = id.substring(id.indexOf('/') + 1); 83: return idCity.replace('_', ' ').equals(city); 84: } 85: 86: private DateFormat timeFormatter; 87: private Date theDate; 88: private String city; 89: }
previous | start | next The Output of the Time Zone JSP Page previous | start | next
HTML Forms • An HTML form contains user interface elements such as: • o Text fields • o Password fields • o Text areas • o Radio buttons • o Check boxes • o Selection lists • o Submit buttons • o Hidden fields
HTML Forms • Most form elements have the syntax • <input type=type_nameadditional_attributes/> • You should include a name attribute on every element except submit button • You may include a value attribute with a default value
HTML Forms • Text field • <input type="text" name="country" value="USA" size="16" maxlength="16" /> • Password • <input type="password" name="accountnumber" size="16" maxlength="16" /> • Text area • <textarea name="..." rows="..." cols="..."> default text • </textarea>
HTML Forms • Radio button • <input type="radio" name="shirtsize" value="S"/>Small • <input type="radio" name="shirtsize" value="M"/>Medium • <input type="radio" name="shirtsize" value="L" checked="checked"/>Large • <input type="radio" name="shirtsize" value="XL"/>Extra large • Only one radio button can be checked at a time • Check box • <input type="checkbox" name="toppings" value="mushrooms" checked="checked"/>Mushrooms • <input type="checkbox" name="toppings" value="anchovies" />Anchovies • More than one checkbox in a group can have the checked attribute set to "checked" • If both boxes are checked the browser sends the server toppings=mushrooms+toppings=anchovies
HTML Forms • Selection list • <select name="month"> • <option value="1" selected="selected">January</option> <option value="2" >February</option> • <option value="3" >March</option> • <option value="4" >April</option> • . • . • . • <option value="12" >December</option> • </select>
Submit button • <input type="submit" value="Get time"/> • Hidden field • <input type="hidden" name="accountnumber" value="YYY-11543-234-9"/> • The browser does not display a hidden field • It sends the name/value pairs in the field to the server when the form is submitted
HTML Forms • Place all elements that belong to a form into a form element <form action="timezone.jsp" method="POST"> • . • . • . • </form> • An HTML form must specify the URL of the server program that processes the form data • The action attribute contains the URL • Set the method attribute to POST because it has no length • limit
Session Tracking • A session is a sequence of page requests from the same browser to the same web server • To track a session in a sequence of JSP pages, use a bean with session scope <jsp:useBean id="cart" class="ShoppingCartBean" scope="session"/> • The user requests the JSP page containing this directive for the first time • A new cart object is constructed • The user returns to the same page or visits another page in the same application • The cart object is still alive • If the bean directive has no scope attribute • The bean object has page scope • A new object is created every time the page is visited
Session Tracking • Create a program that allows the user to keep adding cities and their time zones • In the initial HTML form, the web application asks for the name of the first city • The JSP page displays the first city and a form to enter another city • The user can add as many cities as he likes • All cities are stored in an object of the MultiZoneBean class
Session Tracking • The bean object has session scope and so holds a list of all the cities • Keep cities in a MultiZoneBean <jsp:useBean id="zones" class="MultiZoneBean" scope="session"/> • An instance is created for each session • The setCity method adds a city to the bean object • The new city is the value of the text field whose name is city <jsp:setProperty name="zones" property="city" param="city"/>
File multizone.html 01: <html> 02: <head> 03: <title>Multiple Time Zone Form</title> 04: </head> 05: <body> 06: <form action="multizone.jsp" 07: method="POST"> 08: <p>First City: 09: <input type="text" name="city"/> 10: <input type="submit" value="Add City"/> 11: </p> 12: </form> 13: </body> 14: </html>
File multizone.jsp 01: <jsp:useBean id="zones" class="MultiZoneBean" scope="session"/> 02: <jsp:setProperty name="zones" property="date" value="<%= new java.util.Date() %>"/> 03: <jsp:setProperty name="zones" property="city" param="city"/> 04: <jsp:setProperty name="zones" property="city" value="<jsp:getProperty name=\"zones\" property=\"times\"/>"/> 05: 06: <html> 07: <head> 08: <title>Multiple Time Zone JSP</title> 09: </head> 10: <body> 11: <h1>Current time lookup</h1> 12: <ul> 13: <jsp:getProperty name="zones" property="times"/> 14: </ul>
15: <form action="multizone.jsp" 16: method="POST"> 17: <p>Next City: 18: <input type="text" name="city"/> 19: <input type="submit" value="Add City"/> 20: </p> 21: </form> 22: </body> 23: </html>