servlet - wordpress.comservlet life cycle • the life cycle of a servlet is controlled by the...
TRANSCRIPT
Servlet
Outline
bull Introduction
bull Interface Servlet and the Servlet Life Cycle
bull HttpServlet Class
bull HttpServletRequest Interface
bull HttpServletResponse Interface
bull Handling HTTP get Requests
bull Deploying a Web Application
bull Handling HTTP get Requests Containing Data
bull Handling HTTP post Requests
bull Redirecting Requests to Other Resources
bull Multi-Tier Applications Using JDBC from a Servlet
Server-side Java for the web
bull a servlet is a Java program which outputs an html page it is
a server-side technology
browser web server
HTTP Request
HTTP Response
Server-side Request
Response Header +
Html file
Java Servlet
Java Server Page
servlet container
(engine) -
Tomcat
Introduction
bull A servlet is a Java programming language class that is
used to extend the capabilities of servers that host
applications accessed by means of a request-response
programming model
bull Although servlets can respond to any type of request they
are commonly used to extend the applications hosted by
web servers For such applications Java Servlet
technology defines HTTP-specific servlet classes
Introduction
bull The javaxservlet and javaxservlethttp packages provide
interfaces and classes for writing servlets
bull All servlets must implement the Servlet interface which
defines life-cycle methods
bull When implementing a generic service you can use or extend
the GenericServlet class provided with the Java Servlet API
bull The HttpServlet class provides methods such
as doGet and doPost for handling HTTP-specific services
Working of Servlet
bull Client sends HTTP request
bull Servlet container receives request directs it to the
appropriate servlet
bull Servlet does processing (including interacting with
databases)
bull Servlet returns results to client in form of HTML
document
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Outline
bull Introduction
bull Interface Servlet and the Servlet Life Cycle
bull HttpServlet Class
bull HttpServletRequest Interface
bull HttpServletResponse Interface
bull Handling HTTP get Requests
bull Deploying a Web Application
bull Handling HTTP get Requests Containing Data
bull Handling HTTP post Requests
bull Redirecting Requests to Other Resources
bull Multi-Tier Applications Using JDBC from a Servlet
Server-side Java for the web
bull a servlet is a Java program which outputs an html page it is
a server-side technology
browser web server
HTTP Request
HTTP Response
Server-side Request
Response Header +
Html file
Java Servlet
Java Server Page
servlet container
(engine) -
Tomcat
Introduction
bull A servlet is a Java programming language class that is
used to extend the capabilities of servers that host
applications accessed by means of a request-response
programming model
bull Although servlets can respond to any type of request they
are commonly used to extend the applications hosted by
web servers For such applications Java Servlet
technology defines HTTP-specific servlet classes
Introduction
bull The javaxservlet and javaxservlethttp packages provide
interfaces and classes for writing servlets
bull All servlets must implement the Servlet interface which
defines life-cycle methods
bull When implementing a generic service you can use or extend
the GenericServlet class provided with the Java Servlet API
bull The HttpServlet class provides methods such
as doGet and doPost for handling HTTP-specific services
Working of Servlet
bull Client sends HTTP request
bull Servlet container receives request directs it to the
appropriate servlet
bull Servlet does processing (including interacting with
databases)
bull Servlet returns results to client in form of HTML
document
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Server-side Java for the web
bull a servlet is a Java program which outputs an html page it is
a server-side technology
browser web server
HTTP Request
HTTP Response
Server-side Request
Response Header +
Html file
Java Servlet
Java Server Page
servlet container
(engine) -
Tomcat
Introduction
bull A servlet is a Java programming language class that is
used to extend the capabilities of servers that host
applications accessed by means of a request-response
programming model
bull Although servlets can respond to any type of request they
are commonly used to extend the applications hosted by
web servers For such applications Java Servlet
technology defines HTTP-specific servlet classes
Introduction
bull The javaxservlet and javaxservlethttp packages provide
interfaces and classes for writing servlets
bull All servlets must implement the Servlet interface which
defines life-cycle methods
bull When implementing a generic service you can use or extend
the GenericServlet class provided with the Java Servlet API
bull The HttpServlet class provides methods such
as doGet and doPost for handling HTTP-specific services
Working of Servlet
bull Client sends HTTP request
bull Servlet container receives request directs it to the
appropriate servlet
bull Servlet does processing (including interacting with
databases)
bull Servlet returns results to client in form of HTML
document
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Introduction
bull A servlet is a Java programming language class that is
used to extend the capabilities of servers that host
applications accessed by means of a request-response
programming model
bull Although servlets can respond to any type of request they
are commonly used to extend the applications hosted by
web servers For such applications Java Servlet
technology defines HTTP-specific servlet classes
Introduction
bull The javaxservlet and javaxservlethttp packages provide
interfaces and classes for writing servlets
bull All servlets must implement the Servlet interface which
defines life-cycle methods
bull When implementing a generic service you can use or extend
the GenericServlet class provided with the Java Servlet API
bull The HttpServlet class provides methods such
as doGet and doPost for handling HTTP-specific services
Working of Servlet
bull Client sends HTTP request
bull Servlet container receives request directs it to the
appropriate servlet
bull Servlet does processing (including interacting with
databases)
bull Servlet returns results to client in form of HTML
document
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Introduction
bull The javaxservlet and javaxservlethttp packages provide
interfaces and classes for writing servlets
bull All servlets must implement the Servlet interface which
defines life-cycle methods
bull When implementing a generic service you can use or extend
the GenericServlet class provided with the Java Servlet API
bull The HttpServlet class provides methods such
as doGet and doPost for handling HTTP-specific services
Working of Servlet
bull Client sends HTTP request
bull Servlet container receives request directs it to the
appropriate servlet
bull Servlet does processing (including interacting with
databases)
bull Servlet returns results to client in form of HTML
document
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Working of Servlet
bull Client sends HTTP request
bull Servlet container receives request directs it to the
appropriate servlet
bull Servlet does processing (including interacting with
databases)
bull Servlet returns results to client in form of HTML
document
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Structure of Web Modules
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Interface Servlet
bull Interface Servlet
ndash All servlets must implement this interface
ndash All methods of interface Servlet are invoked by servlet
container
bull Servlet implementation (two abstract classes
implement Servlet interface)
ndash GenericServlet (javaxservlet)
ndash HttpServlet (javaxservlethttp)
ndash service method
public void service(ServletRequest req ServletResponse res)
bull ServletRequest object is data from client
bull ServletResponse object is data to the client
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Servlet Life Cycle
bull The life cycle of a servlet is controlled by the container in
which the servlet has been deployed
bull When a request is mapped to a servlet the container
performs the following steps
bull If an instance of the servlet does not exist the web container
ndash Loads the servlet class
ndash Creates an instance of the servlet class
ndash Initializes the servlet instance by calling the init method
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Servlet Life Cycle
ndash Servletrsquos service method handles requests (receives
processes sends response to client)
ndash Servletrsquos service method called once per request runs in
a Thread
ndash Servletrsquos destroy method releases servlet resources when
the servlet container terminates the servlet
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Interface Servlet and the Servlet Life Cycle
Method Description void init( ServletConfig config )
The servlet container calls this method once during a servletrsquos execution cycle to initialize the
servlet The ServletConfig argument is supplied by the servlet container that executes the
servlet ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig This
object provides access to the servletrsquos configuration information such as servlet initialization
parameters and the servletrsquos ServletContext which provides the servlet with access to its
environment (ie the servlet container in which the servlet executes)
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information
such as the servletrsquos author and version void service( ServletRequest request ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet
void destroy()
This ldquocleanuprdquo method is called when a servlet is terminated by its servlet container Resources
used by the servlet such as an open file or an open database connection should be deallocated here
Methods of interface Servlet (package javaxservlet)
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
HttpServlet Class
bull Web-based servlets typically extend HttpServlet
class
bull HttpServlet overrides method service
bull Two most common HTTP request types
ndash get requests (data rides on URL)
ndash post requests (data sent in a file)
bull Method doGet responds to get requests
public void doGet(HttpServletRequest request
HttpServletResponse response)
bull Method doPost responds to post requests
public void doPost(HttpServletRequest request
HttpServletResponse response)
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
HttpServlet Class
bull HttpServletRequest and
HttpServletResponse objects enable
interaction between client and server
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
HttpServletRequest Interface
bull Web server
ndash creates an HttpServletRequest object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
ndash HttpServletRequest object contains the request from
the client
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
HttpServletRequest Interface
Method Description String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request The
name argument represents the parameter name Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request
String[] getParameterValues( String name )
For a parameter with multiple values this method returns an array of strings containing the
values for a specified servlet parameter Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server Cookie objects can
be used to uniquely identify clients to the servlet HttpSession getSession( boolean create )
Returns an HttpSession object associated with the clientrsquos current browsing session
This method can create an HttpSession object (true argument) if one does not already
exist for the client HttpSession objects are used in similar ways to Cookies for
uniquely identifying clients
Fig 243 Some methods of interface HttpServletRequest
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
HttpServletResponse Interface
bull Web server
ndash creates an HttpServletResponse object
ndash passes it to the servletrsquos service method (that is doGet
or doPost)
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
HttpServletResponse Interface
Method Description void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client The
Cookiersquos maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client void setContentType( String type )
Specifies the MIME type of the response to the browser The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data) For example MIME type
texthtml indicates that the response is an HTML document so the
browser displays the HTML page
Fig 244 Some methods of interface HttpServletResponse
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Handling HTTP get Requests
bull get request
ndash May send data on the URL this example does not
bull Example WelcomeServlet
ndash a servlet handles HTTP get requests
ndash responsesetContentType(texthtml)
provides the browser with Multipurpose Internet Mail
Extension (MIME) type
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 WelcomeServletjava
2 A simple servlet to process get requests
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet extends HttpServlet
9
10 process get requests from clients
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 responsesetContentType( texthtml )
16 PrintWriter out = responsegetWriter()
17
18 send HTML page to client
19
20 start HTML document
21
22
23
24
25
26
Import the javaxservlet and
javaxservlethttp packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to
provide custom get request
processing
Uses the response objectrsquos
setContentType method to
specify the content type of the data to
be sent as the response to the client
Uses the response objectrsquos
getWriter method to obtain a
reference to the PrintWriter
object that enables the servlet to send
content to the client
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
27 outprintln( lthtmlgt )
28
29 head section of document
30 outprintln( ltheadgt )
31 outprintln( lttitlegtA Simple Servlet Examplelttitlegt )
32 outprintln( ltheadgt )
33
34 body section of document
35 outprintln( ltbodygt )
36 outprintln( lth1gtWelcome to Servletslth1gt )
37 outprintln( ltbodygt )
38
39 end HTML document
40 outprintln( lthtmlgt )
41 outclose() close stream to complete the page
42
43
Closes the output stream
flushes the output buffer
and sends the information
to the client
Create the HTML document by
writing strings with the out
objectrsquos println method
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- WelcomeServlethtml --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Get Requestlttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome1 method = getgt
14
15 ltpgtltlabelgtClick the button to invoke the servlet
16 ltinput type = submit value = Get HTML Document gt
17 ltlabelgtltpgt
18
19 ltformgt
20 ltbodygt
21 lthtmlgt
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Program
output
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Deploying a Web Application
bull Web applications
ndash JSPs servlets and their supporting files
bull Deploying a Web application
ndash Deployment descriptor
bull webxml
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 ltDOCTYPE web-app PUBLIC
2 -Sun Microsystems IncDTD Web Application 22EN
3 httpjavasuncomj2eedtdsweb-app_2_2dtdgt
4
5 ltweb-appgt
6
7 lt-- General description of your Web application --gt
8 ltdisplay-namegt
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 ltdisplay-namegt
12
13 ltdescriptiongt
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples
16 ltdescriptiongt
17
18 lt-- Servlet definitions --gt
19 ltservletgt
20 ltservlet-namegtwelcome1ltservlet-namegt
21
22 ltdescriptiongt
23 A simple servlet that handles an HTTP get request
24 ltdescriptiongt
25
Element web-app defines the configuration
of each servlet in the Web application and
the servlet mapping for each servlet
Element display-name specifies
a name that can be displayed to the
administrator of the server on which
the Web application is installed
Element description specifies a
description of the Web application
that might be displayed to the
administrator of the server
Element servlet describes a servlet
Element servlet-name
is the name for the servlet
Element description
specifies a description for
this particular servlet
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
26 ltservlet-classgt
27 WelcomeServlet
28 ltservlet-classgt
29 ltservletgt
30
31 lt-- Servlet mappings --gt
32 ltservlet-mappinggt
33 ltservlet-namegtwelcome1ltservlet-namegt
34 lturl-patterngtwelcome1lturl-patterngt
35 ltservlet-mappinggt
36
37 ltweb-appgt
Element servlet-mapping
specifies servlet-name and
url-pattern elements
Element servlet-class
specifies compiled servletrsquos
fully qualified class name
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Handling HTTP get Requests Containing
Data
bull Servlet WelcomeServlet2
ndash Responds to a get request that contains data
ndash Parameters passed as namevalue pairs on the URL
(httpwelcome2firstname=Paul)
ndash String firstName =
requestgetParameter(firstname)
bull retrieves the string ldquoPaulrdquo
bull retrieves null if no parameter has the name firstname
bull parameters typically come from HTML FORMs
bull servlet is called when SUBMIT button is clicked
ndash Multiple parameters separated by amprsquos
(httpwelcome2firstname=Paulamplastn
ame=Davisampidnum=22471)
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 WelcomeServlet2java
2 Processing HTTP get requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet2 extends HttpServlet
9
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML document to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
The request objectrsquos
getParameter
method receives the
parameter name and
returns the
corresponding String
value
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing get requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end XHTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
Uses the result of line
15 as part of the
response to the client
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2412 WelcomeServlet2html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtProcessing get requests with datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome2 method = getgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltpgtltlabelgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Get the first name
from the user
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Handling HTTP post Requests
bull HTTP post request
ndash Post data from an HTML form to a server-side form handler
using a file
ndash Browsers usually do NOT cache post requests
bull Search engines usually use ldquogetrdquo because just a
little data
ndash Browsers usually cache get requests
bull Servlet WelcomeServlet3
ndash Responds to a post request that contains data
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 WelcomeServlet3java
2 Processing post requests containing data
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
7
8 public class WelcomeServlet3 extends HttpServlet
9
10 process post request from client
11 protected void doPost( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String firstName = requestgetParameter( firstname )
16
17 responsesetContentType( texthtml )
18 PrintWriter out = responsegetWriter()
19
20 send HTML page to client
21
22 start HTML document
23 outprintln( ltxml version = 10gt )
24
Declare a doPost method
to responds to post requests
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
25 outprintln( ltDOCTYPE html PUBLIC -W3CDTD +
26 XHTML 10 StrictEN httpwwww3org +
27 TRxhtml1DTDxhtml1-strictdtdgt )
28
29 outprintln( lthtml xmlns = httpwwww3org1999xhtmlgt )
30
31 head section of document
32 outprintln( ltheadgt )
33 outprintln(
34 lttitlegtProcessing post requests with datalttitlegt )
35 outprintln( ltheadgt )
36
37 body section of document
38 outprintln( ltbodygt )
39 outprintln( lth1gtHello + firstName + ltbr gt )
40 outprintln( Welcome to Servletslth1gt )
41 outprintln( ltbodygt )
42
43 end HTML document
44 outprintln( lthtmlgt )
45 outclose() close stream to complete the page
46
47
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 ltxml version = 10gt
2 ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN
3 httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgt
4
5 lt-- Fig 2415 WelcomeServlet3html --gt
6
7 lthtml xmlns = httpwwww3org1999xhtmlgt
8 ltheadgt
9 lttitlegtHandling an HTTP Post Request with Datalttitlegt
10 ltheadgt
11
12 ltbodygt
13 ltform action = jhtp5welcome3 method = postgt
14
15 ltpgtltlabelgt
16 Type your first name and press the Submit button
17 ltbr gtltinput type = text name = firstname gt
18 ltinput type = submit value = Submit gt
19 ltlabelgtltpgt
20
21 ltformgt
22 ltbodygt
23 lthtmlgt
Provide a form in which the
user can input a name in the
text input element
firstname then click the
Submit button to invoke
WelcomeServlet3
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Redirecting Requests to Other Resources
bull Servlet RedirectServlet
ndash Redirects the request to a different resource
ndash responsesendRedirect(URL)
bull redirects to that URL
bull immediately terminates current program
bull Use relative paths whenever possible to make Website portable
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
1 RedirectServletjava
2 Redirecting a user to a different Web page
3
4 import javaxservlet
5 import javaxservlethttp
6 import javaio
8 public class RedirectServlet extends HttpServlet
10 process get request from client
11 protected void doGet( HttpServletRequest request
12 HttpServletResponse response )
13 throws ServletException IOException
14
15 String location = requestgetParameter( page )
16
17 if ( location = null )
18
19 if ( locationequals( deitel ) )
20 responsesendRedirect( httpwwwdeitelcom )
21 else
22 if ( locationequals( welcome1 ) )
23 responsesendRedirect( welcome1 )
24 outclose()
25
26
Obtains the page
parameter from the request
Determine if the value is either
ldquodeitelrdquo or ldquowelcome1rdquo Redirects the request to
wwwdeitelcom
Redirects the request to the
servlet WelcomeServlet
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Multi-Tier Applications Using JDBC from a
Servlet
bull Servlets can communicate with databases via
JDBC
bull Three-tier distributed applications
ndash User interface
ndash Processing logic
ndash Database access
bull HTML user interface makes interface very
accessible across multiple platforms
bull Web servers often represent the middle tier
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Multi-Tier Applications Using JDBC from a
Servlet
bull Three-tier distributed application example
ndash Studenthtml
ndash StudentServlet
ndash student database
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava
Servlet-JDBC Example
Accept the roll number first name and division from
the student using html file and insert these values in
the student table using Servlet
Studenthtml
StudentServletjava