Title: Servlets
1Servlets
2Servlets
- A servlet is a Java program that resides on the
server and sends information back to the client. - For example, a web server sends HTML to a
browser. - The HTML can come from a file on the server or it
can be sent by a program such as a Java servlet.
3Servlets
- Packages for servlets
- javax.servlet defines GenericServlet, which is
protocol-independent. - javax.servlet.http defines HttpServlet, which
uses the HTTP protocol. - Both GenericServlet and HttpServlet implement the
Servlet interface.
4Methods of interface Servlet
5HttpServlet
- The two most common requests from a client web
browser are - Get retrieves information from the server,
usually an HTML document. Handled by HttpServlet
method doGet(). - Post sends information to the server, such as
information from a form. Handled by HttpServlet
method doPost().
6Other HttpServlet Methods
7Other HTTP Interfaces
- Both doGet() and doPost() receive a response and
request object. - The request object implements the
HttpServletRequest interface, and the response
object implements the HttpServletResponse
interface. - These enable the servlet to get the client
request and formulate a response.
8- lt?xml version "1.0"?gt
- lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" - "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
dtd"gt - lt!-- Fig. 26.7 WelcomeServlet.html --gt
- lthtml xmlns "http//www.w3.org/1999/xhtml"gt
- ltheadgt
- lttitlegtHandling an HTTP Get Requestlt/titlegt
- lt/headgt
- ltbodygt
- ltform action "/jhtp6/welcome1" method
"get"gt - ltpgtltlabelgtClick the button to invoke the
servlet - ltinput type "submit" value "Get HTML
Document" /gt - lt/labelgtlt/pgt
- lt/formgt
- lt/bodygt
- lt/htmlgt
9- // Fig. 26.6 WelcomeServlet.java. A simple
servlet to process get requests. - import javax.servlet.ServletException
- import javax.servlet.http.HttpServlet
- import javax.servlet.http.HttpServletRequest
- import javax.servlet.http.HttpServletResponse
- import java.io.IOException
- import java.io.PrintWriter
- public class WelcomeServlet extends HttpServlet
-
- // process "get" requests from clients
- protected void doGet( HttpServletRequest
request, - HttpServletResponse response )
- throws ServletException, IOException
-
- response.setContentType( "text/html" )
- PrintWriter out response.getWriter()
-
- // send XHTML page to client
10- out.println( "lthtml xmlns
\"http//www.w3.org/1999/xhtml\"gt" ) -
- // head section of document
- out.println( "ltheadgt" )
- out.println( "lttitlegtA Simple Servlet
Examplelt/titlegt" ) - out.println( "lt/headgt" )
-
- // body section of document
- out.println( "ltbodygt" )
- out.println( "lth1gtWelcome to
Servlets!lt/h1gt" ) - out.println( "lt/bodygt" )
-
- // end XHTML document
- out.println( "lt/htmlgt" )
- out.close() // close stream to complete
the page - // end method doGet
- // end class WelcomeServlet
11- ltweb-app xmlns"http//java.sun.com/xml/ns/j2ee"
- xmlnsxsi"http//www.w3.org/2001/XMLSchema-ins
tance" - xsischemaLocation"http//java.sun.com/xml/ns/
j2ee - http//java.sun.com/xml/ns/j2ee/web-app_2_4.
xsd" - version"2.4"gt
- lt!-- General description of your Web
application --gt - ltdisplay-namegt
- Java How to Program JSP
- and Servlet Chapter Examples
- lt/display-namegt
- ltdescriptiongt
- This is the Web application in which we
- demonstrate our JSP and Servlet examples.
- lt/descriptiongt
- lt!-- Servlet definitions --gt
- ltservletgt
12Get Requests Containing Data
- A request to the server can also contain data.
- Data comes in the form of parameters.
- Parameters are name-value pairs supplied at the
end of the URL after a question mark. - For example http//localhost?firstnameJon
- Use for multiple parameters.
13- lt?xml version "1.0"?gt
- lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" - "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
dtd"gt - lt!-- Fig. 26.13 WelcomeServlet2.html --gt
- lthtml xmlns "http//www.w3.org/1999/xhtml"gt
- ltheadgt
- lttitlegtProcessing get requests with
datalt/titlegt - lt/headgt
- ltbodygt
- ltform action "/jhtp6/welcome2" method
"get"gt - ltpgtltlabelgt
- Type your first name and press the
Submit button - ltbr /gtltinput type "text" name
"firstname" /gt - ltinput type "submit" value "Submit"
/gt - lt/pgtlt/labelgt
- lt/formgt
14// Fig. 26.12 WelcomeServlet2.java. Processing
HTTP get requests containing data. import
javax.servlet.ServletException import
javax.servlet.http.HttpServlet import
javax.servlet.http.HttpServletRequest import
javax.servlet.http.HttpServletResponse import
java.io.IOException import java.io.PrintWriter
public class WelcomeServlet2 extends HttpServlet
// process "get" request from client
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
String firstName request.getParameter(
"firstname" ) response.setContentTyp
e( "text/html" ) PrintWriter out
response.getWriter() // send
XHTML document to client // start XHTML
document out.println( "lt?xml version
\"1.0\"?gt" )
15 out.printf( "sss", "lt!DOCTYPE html
PUBLIC", " \"-//W3C//DTD XHTML 1.0
Strict//EN\"", " \"http//www.w3.org/TR/x
html1/DTD/xhtml1-strict.dtd\"gt\n" )
out.println( "lthtml xmlns \"http//www.w3.org/19
99/xhtml\"gt" ) // head section of
document out.println( "ltheadgt" )
out.println( "lttitlegtProcessing get requests with
datalt/titlegt" ) out.println( "lt/headgt" )
// body section of document
out.println( "ltbodygt" ) out.println(
"lth1gtHello " firstName ",ltbr /gt" )
out.println( "Welcome to Servlets!lt/h1gt" )
out.println( "lt/bodygt" ) // end
XHTML document out.println( "lt/htmlgt" )
out.close() // close stream to complete the
page // end method doGet // end class
WelcomeServlet2
16Post Requests
- The next example shows how to handle a post
request. - The example is identical to before, except for
the doPost() instead of doGet(). - This is because the classes are hiding some of
the differences between these two kinds of
requests.
17- lt?xml version "1.0"?gt
- lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" - "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
dtd"gt - lt!-- Fig. 26.16 WelcomeServlet3.html --gt
- lthtml xmlns "http//www.w3.org/1999/xhtml"gt
- ltheadgt
- lttitlegtHandling an HTTP Post Request with
Datalt/titlegt - lt/headgt
- ltbodygt
- ltform action "/jhtp6/welcome3" method
"post"gt - ltpgtltlabelgt
- Type your first name and press the
Submit button - ltbr /gtltinput type "text" name
"firstname" /gt - ltinput type "submit" value "Submit"
/gt - lt/labelgtlt/pgt
- lt/formgt
18// Fig. 26.15 WelcomeServlet3.java. Processing
post requests containing data. import
javax.servlet.ServletException import
javax.servlet.http.HttpServlet import
javax.servlet.http.HttpServletRequest import
javax.servlet.http.HttpServletResponse import
java.io.IOException import java.io.PrintWriter
public class WelcomeServlet3 extends
HttpServlet // process "post" request
from client protected void doPost(
HttpServletRequest request, HttpServletResponse
response ) throws ServletException,
IOException String firstName
request.getParameter( "firstname" )
response.setContentType( "text/html" )
PrintWriter out response.getWriter()
// send XHTML page to client // start
XHTML document out.println( "lt?xml version
\"1.0\"?gt" )
19 out.printf( "sss", "lt!DOCTYPE html
PUBLIC", " \"-//W3C//DTD XHTML 1.0
Strict//EN\"", " \"http//www.w3.org/TR/x
html1/DTD/xhtml1-strict.dtd\"gt\n" )
out.println( "lthtml xmlns \"http//www.w3.org/19
99/xhtml\"gt" ) // head section of
document out.println( "ltheadgt" )
out.println( "lttitlegtProcessing post requests
with datalt/titlegt" ) out.println(
"lt/headgt" ) // body section of
document out.println( "ltbodygt" )
out.println( "lth1gtHello " firstName ",ltbr /gt"
) out.println( "Welcome to Servlets!lt/h1gt"
) out.println( "lt/bodygt" )
// end XHTML document out.println(
"lt/htmlgt" ) out.close() // close stream
to complete the page // end method doPost
// end class WelcomeServlet3
20Redirecting Requests
- Sometimes a request is redirected to another
place, such as to a different server or web page. - The response objects sendRedirect() method
accomplishes this. - The next example illustrates this
21- lt?xml version "1.0"?gt
- lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" - "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
dtd"gt - lt!-- Fig. 26.19 RedirectServlet.html --gt
- lthtml xmlns "http//www.w3.org/1999/xhtml"gt
- ltheadgt
- lttitlegtRedirecting a Request to Another
Sitelt/titlegt - lt/headgt
- ltbodygt
- ltpgtClick a link to be redirected to the
appropriate pagelt/pgt - ltpgt
- lta href "/jhtp6/redirect?pagedeitel"gt
- www.deitel.comlt/agtltbr /gt
- lta href "/jhtp6/redirect?pagewelcome1"gt
- Welcome servletlt/agt
- lt/pgt
22// Fig. 26.18 RedirectServlet.java. Redirecting
a user to a different Web page. import
javax.servlet.ServletException import
javax.servlet.http.HttpServlet import
javax.servlet.http.HttpServletRequest import
javax.servlet.http.HttpServletResponse import
java.io.IOException import java.io.PrintWriter
public class RedirectServlet extends HttpServlet
// process "get" request from client
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws
ServletException, IOException String
location request.getParameter( "page" )
if ( location ! null ) if (
location.equals( "deitel" ) )
response.sendRedirect( "http//www.deitel.com"
) else if ( location.equals( "welcome1"
) ) response.sendRedirect( "welcome1"
) // end if
23 // code that executes only if this servlet
does not redirect the user to another page
response.setContentType( "text/html" )
PrintWriter out response.getWriter()
// start XHTML document out.println( "lt?xml
version \"1.0\"?gt" ) out.printf(
"sss", "lt!DOCTYPE html PUBLIC", "
\"-//W3C//DTD XHTML 1.0 Strict//EN\"", "
\"http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dt
d\"gt\n" ) out.println( "lthtml xmlns
\"http//www.w3.org/1999/xhtml\"gt" ) //
head section of document out.println(
"ltheadgt" ) out.println( "lttitlegtInvalid
pagelt/titlegt" ) out.println( "lt/headgt" )
24- // body section of document
- out.println( "ltbodygt" )
- out.println( "lth1gtInvalid page
requestedlt/h1gt" ) - out.println( "ltpgtlta href "
- "\"servlets/RedirectServlet.html\"gt" )
- out.println( "Click here to choose
againlt/agtlt/pgt" ) - out.println( "lt/bodygt" )
- // end XHTML document
- out.println( "lt/htmlgt" )
- out.close() // close stream to complete
the page - // end method doGet
- // end class RedirectServlet
25Two-tier Architecture
- A program may consist of a GUI interface, logic
to process requests, and a database to store
requests. - Traditionally, these might be constructed as
two-tiers. - The GUI and logic are in one tier, the database
is in the other
DB
Client
Fat client
26Three-tier Architecture
- If the client is broken into two pieces, then the
architecture becomes three-tier. - One piece is a thin client, which means a client
with very little logic, such as a web browser,
mostly responsible for presentation. - The other piece is the application logic which
resides on a server.
DB
Client
Logic
Thin client
27JDBC with Servlets
- A web page interacting with a servlet that uses
JDBC to interact with a database can act as a
three-tier architecture. - The next example illustrates this
28- lt?xml version "1.0"?gt
- lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" - "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
dtd"gt - lt!-- Fig 26.22 Survey.html --gt
- lthtml xmlns "http//www.w3.org/1999/xhtml"gt
- ltheadgt
- lttitlegtSurveylt/titlegt
- lt/headgt
- ltbodygt
- ltform method "post" action "/jhtp6/animalsurve
y"gt - ltpgtWhat is your favorite pet?lt/pgt
- ltpgt
- ltinput type "radio" name "animal"
- value "1" /gtDogltbr /gt
- ltinput type "radio" name "animal"
- value "2" /gtCatltbr /gt
29// Fig. 26.21 SurveyServlet.java // A Web-based
survey that uses JDBC from a servlet. package
com.deitel.jhtp6.servlets import
java.io.PrintWriter import java.io.IOException i
mport java.sql.Connection import
java.sql.DriverManager import java.sql.Statement
import java.sql.ResultSet import
java.sql.SQLException import javax.servlet.Servle
tConfig import javax.servlet.ServletException im
port javax.servlet.UnavailableException import
javax.servlet.http.HttpServlet import
javax.servlet.http.HttpServletRequest import
javax.servlet.http.HttpServletResponse public
class SurveyServlet extends HttpServlet
private Connection connection private
Statement statement
30 // set up database connection and create SQL
statement public void init( ServletConfig
config ) throws ServletException //
attempt database connection and create Statement
try Class.forName(
config.getInitParameter( "databaseDriver" ) )
connection DriverManager.getConnection(
config.getInitParameter(
"databaseName" ), config.getInitParame
ter( "username" ), config.getInitParam
eter( "password" ) ) // create
Statement to query database statement
connection.createStatement() // end try
// for any exception throw an
UnavailableException to // indicate that
the servlet is not currently available
catch ( Exception exception )
exception.printStackTrace() throw new
UnavailableException( exception.getMessage() )
// end catch // end method init
Provided to server
31 // process survey response protected void
doPost( HttpServletRequest request,
HttpServletResponse response ) throws
ServletException, IOException // set
up response to client response.setContentTyp
e( "text/html" ) PrintWriter out
response.getWriter() // start XHTML
document out.println( "lt?xml version
\"1.0\"?gt" ) out.printf( "sss",
"lt!DOCTYPE html PUBLIC", "
\"-//W3C//DTD XHTML 1.0 Strict//EN\"", "
\"http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dt
d\"gt\n" ) out.println( "lthtml xmlns
\"http//www.w3.org/1999/xhtml\"gt" ) //
head section of document out.println(
"ltheadgt" ) // read current survey
response int value Integer.parseInt(
request.getParameter( "animal" ) ) String
sql
32 // attempt to process a vote and display
current results try //
update total for current survey response
sql "UPDATE surveyresults SET votes votes 1
" "WHERE id " value
statement.executeUpdate( sql ) // get
total of all survey responses sql
"SELECT sum( votes ) FROM surveyresults"
ResultSet totalRS statement.executeQuery( sql
) totalRS.next() // position to first
record int total totalRS.getInt( 1
) // get results sql
"SELECT surveyoption, votes, id FROM
surveyresults " "ORDER BY id"
ResultSet resultsRS statement.executeQuery( sql
) out.println( "lttitlegtThank
you!lt/titlegt" ) out.println( "lt/headgt"
) out.println( "ltbodygt" )
out.println( "ltpgtThank you for
participating." ) out.println( "ltbr
/gtResultslt/pgtltpregt" )
33 // process results int votes
while ( resultsRS.next() )
out.print( resultsRS.getString(
1 ) ) out.print( " " )
votes resultsRS.getInt( 2 )
out.printf( ".2f", ( double ) votes / total
100 ) out.print( " responses "
) out.println( votes )
// end while resultsRS.close()
out.print( "Total responses " )
out.print( total ) // end
XHTML document out.println(
"lt/pregtlt/bodygtlt/htmlgt" )
out.close() // end try
34 // if database exception occurs, return
error page catch ( SQLException
sqlException )
sqlException.printStackTrace()
out.println( "lttitlegtErrorlt/titlegt" )
out.println( "lt/headgt" ) out.println(
"ltbodygtltpgtDatabase error occurred. " )
out.println( "Try again later.lt/pgtlt/bodygtlt/htmlgt"
) out.close() // end catch
// end method doPost
35- // close SQL statements and database when
servlet terminates - public void destroy()
-
- // attempt to close statements and database
connection - try
-
- statement.close()
- connection.close()
- // end try
- // handle database exceptions by returning
error to client - catch( SQLException sqlException )
-
- sqlException.printStackTrace()
- // end catch
- // end method destroy
- // end class SurveyServlet
36End of Slides