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
File date.jsp
Executing the Date Page

To Deploy the Date Page
- Type the JSP file into a text editor
- Place the file into a web application directory of your JSP engine
- If you use Tomcat, create a subdirectory for the JSP file
c:\jakarta-tomcat\webapps\bigjava
- Place the date.jsp file into that directory
- Start the web server
- 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
The JSP Container Rewrites the Requested Page

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
Encapsulating Computations in JavaBeans
Encapsulating Computations in JavaBeans
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
File TimeFormatterBean.Java
File time.jsp
Encapsulating Computations in JavaBeans
Handling Request Parameters
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
File timezone.html
The HTML Form for Entering City Names

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
File timezone.jsp
File TimeZoneBean.java
The Output of the Time Zone JSP Page

HTML Forms
- An HTML form contains user interface elements such as:
- Text fields
- Password fields
- Text areas
- Radio buttons
- Check boxes
- Selection lists
- Submit buttons
- Hidden fields
The HTML Form Elements

HTML Forms
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
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
Session Tracking
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
Asking for the First of Several Cities

Asking for the Next City

Display the Time in Multiple Locations

File multizone.html
File multizone.jsp
File MultiZoneBean.java
Branching and Forwarding Pages
- A JSP page can forward a request to another page
- You can use forwarding to implement branches
- Post the query to a JSP page that checks the input but has no HTML output
- The page evaluates the input and uses the jsp:forward directive
to select another page
Branching and Forwarding Pages
Branching and Forwarding Pages
- We can use this technique to handle cities for which no time zone is known
- Start with the same HTML form
- Use the same html
- Except post the data to a non-visual JSP page
- This page then forwards the request to the proper page
File zonebranch.html
File zonebranch.jsp
File zoneresult.jsp
File zoneerror.jsp
A Three-Tier Application
- The presentation tier: the web browser
- The business logic tier: the JSP engine, JSP pages, and the JavaBean
- The storage tier: the database
A Three-Tier Application
- Database table CityZone
- ZoneDBBean consults this database to find the user requested city
- If not available, it looks through the ID's as MultiZoneBean did
- Use a DataSourceBean to manage the database connection
A Three-Tier Application
- Only one instance of DataSourceBean needed for all JSP pages that make
up the web application
- Set its scope to "application"
- Store the database properties in the file web.xml in the WEB_INF
subdirectory
- The JSP pages can access the information in web.xml
- Use the getInitParameter method of the predefined application
object
A Three-Tier Application
- Retrieve the database information from web.xml and initialize
the database
- Any directives you place as child elements of the jsp:useBean element
are executed only once
- ZoneDBBean makes a database query to find the requested city
File zonedb.html
File zonedb.jsp
File DataSourceBean.Java
File ZoneDBBean.Java
Servlets
- Servlets are an alternative to JSPs for building web applications
- JSP pages are actually translated into Servlets
- A servlet is a Java program
- It carries out computations
- And can emit data that is returned to the browser
Servlets
- A servlet is a class that extends HTTPServlet class
- To handle GET requests, a servlet implements doGet
void doGet( HttpServletRequest request,
HttpServletResponse response)
- To handle POST requests, a servlet implements doPost
void doPost( HttpServletRequest request,
HttpServletResponse response)
Servlets
- This example does not receive any request information
- The servlet
- Obtains the current time
- Creates HTML document containing the information
- Sends the page back to the browser
Servlets
- The request parameter contains information about the request
- The response parameter lets you specify what to send back to the browser
Servlets
File DateServlet.Java
Servlets
- To deploy a servlet, you need to write a deployment descriptor
- The deployment descriptor gives the servlet a name
- The name may be different than the class name
- The deployment descriptor tells how to locate the servlet class
- The deployment descriptor tells which URL's map to the servlet
Servlets
- The deployment descriptor must be in the web.xml file
- The web.xml file goes in the WEB-INF subdirectory of the
web application directory
- Put the class files into the classes subdirectory of the WEB-INF
directory
Placement of Web Application Files

Servlets
- This second servlet lets the user supply a city name
- Use the request parameter of the doPost method to get the value
- Use the getParameter method of the request object
File zoneservlet.html
File TimeZoneServlet.Java
Compilation of JSP Pages
- The JSP container translates the JSP pages into servlets
- This happens when the page is first requested
- Also whenever the page has changed
- Bean directives translate into Java code