Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 105

Java Web

Programming

By: Huda Mohamed Yousif


What is Web Programming
• Writing, markup and coding

• Content, client and server scripting, security.

• XML, HTML, JavaScript, Perl 5 and PHP.

• application area, scripting, and database.

• Client & server coding


Client Side Programming
• User Data

• Plug ins for UX and GUI on client

• JavaScript

• HTML5 and CSS3


Server Side Programming
• Data retrieval, security and performance.

• ASP, Lotus Notes, PHP, Java and MySQL.

• Both : Opa and Tersus.


Web Server VS Application Server VS
Web Containers
• Web server
HTTP requests and responses.
Apache and IIS

• Application server
Web applications.
Oracle WebLogic, IBM WebSphere

• Servlet container
servlets life cycle
part of an application server
(Tomcat , Jetty)
Responsibility
• Web servers static content

• Application server dynamic content, EJB ,


distributed transaction, lookup over JNDI, security

• Web containers HTML  JSP and Servlet


Service
• Web server HTTP protocol service

• Application server dynamic Web service and


business level service (EJB)

• Web containers Database connection pooling


Usage
• Web server static web pages

• Web containers JSP and Servlet  generate


dynamic content

• application server Java EE application  EJB,


distributed transaction, messaging
Apache Tomcat
• free, open-source servlet container.

• Servlet containers  runtime environment  servlets.

• Servlet life cycle

• Servlet  functionality of web server.

• dynamic content, processing requests

• Request & responce


Tomcat and WebLogic
• Tomcat application server  highly dynamic
content.

• Tomcat standalone web server

• Tomcat is not a full-featured

• No enterprise-level features (EJBs , Java APIs)

• Full application server  WebLogic


Introduction
• Java networking capabilities
– Socket-based and packet-based communications
• Package java.net
– Remote Method Invocation (RMI)
• Package java.rmi
– Servlets and Java Server Pages (JSP)
• Request-response model
• Packages javax.servlet
javax.servlet.http
javax.servlet.jsp
javax.servlet.tagext
• Form the Web tier of J2EE
Role of Servlets in Web
Programming
• Servlet  create a web application.
• Servlet  API
• Servlet  interface
• Servlet  extends servers capabilities
• Servlet is a web component that is deployed on the
server to create a dynamic web page.
Servlet Life Cycle
1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.


How a Servlet works
How a Servlet works
Interface Servlet and the
Servlet Life Cycle
• Interface Servlet
– All servlets must implement this interface
– All methods of interface Servlet are invoked by servlet
container
• Servlet life cycle
– Servlet container invokes the servlet’s init method
– Servlet’s service method handles requests
– Servlet’s destroy method releases servlet resources when
the servlet container terminates the servlet
• Servlet implementation
– GenericServlet
– HttpServlet
Interface Servlet and the Servlet
Life Cycle (Cont.)
Method Description
void init(
ServletConfig
config )
The servlet container calls this method once during a servlet’s 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 servlet’s configuration information such as servlet initialization
parameters and the servlet’s ServletContext, which provides the servlet with access to its
environment (i.e., 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 servlet’s 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 “cleanup” 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.
Fig. 24.1 Methods of interface Servlet (package javax.servlet).
HttpServlet Class
• Overrides method service
• Two most common HTTP request types
– get requests
– post requests
• Method doGet responds to get requests
• Method doPost responds to post requests
• HttpServletRequest and
HttpServletResponse objects
HttpServlet Class (Cont.)
Method Description
doDelete Called in response to an HTTP delete request. Such a request is normally used
to delete a file from a server. This may not be available on some servers, because
of its inherent security risks (e.g., the client could delete a file that is critical to
the execution of the server or an application).
doHead Called in response to an HTTP head request. Such a request is normally used
when the client only wants the headers of a response, such as the content type and
content length of the response.
doOptions Called in response to an HTTP options request. This returns information to the
client indicating the HTTP options supported by the server, such as the version of
HTTP (1.0 or 1.1) and the request methods the server supports.
doPut Called in response to an HTTP put request. Such a request is normally used to
store a file on the server. This may not be available on some servers, because of
its inherent security risks (e.g., the client could place an executable application on
the server, which, if executed, could damage the server—perhaps by deleting
critical files or occupying resources).
doTrace Called in response to an HTTP trace request. Such a request is normally used
for debugging. The implementation of this method automatically returns an
HTML document to the client containing the request header information (data
sent by the browser as part of the request).
Fig. 24.2 Other methods of class HttpServlet.
HttpServletRequest Interface
• Web server
– creates an HttpServletRequest object
– passes it to the servlet’s service method
• HttpServletRequest object contains the
request from the client
HttpServletRequest Interface
(Cont.)
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 client’s 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. 24.3 Some methods of interface HttpServletRequest.
HttpServletResponse
Interface
• Web server
– creates an HttpServletResponse object
– passes it to the servlet’s service method
24.2.4 HttpServletResponse Interface
(Cont.)
Method Description
void addCookie(
Cookie cookie )
Used to add a Cookie to the header of the response to the client. The
Cookie’s 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
"text/html" indicates that the response is an HTML document, so the
browser displays the HTML page.
Fig. 24.4 Some methods of interface HttpServletResponse.
24.3 Handling HTTP get Requests

• get request
– Retrieve the content of a URL
• Example: WelcomeServlet
– a servlet handles HTTP get requests
1 // Fig. 24.5: WelcomeServlet.java
2 // A simple servlet to process get requests.
3
4 import javax.servlet.*;
5 import javax.servlet.http.*;
6 import java.io.*;
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 response.setContentType( "text/html" );
16 PrintWriter out = response.getWriter();
17
18 // send XHTML page to client
19
20 // start XHTML document
21 out.println( "<?xml version = \"1.0\"?>" );
22
23 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
24 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
25 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
26
27 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
28
29 // head section of document
30 out.println( "<head>" );
31 out.println( "<title>A Simple Servlet Example</title>" );
32 out.println( "</head>" );
33
34 // body section of document
35 out.println( "<body>" );
36 out.println( "<h1>Welcome to Servlets!</h1>" );
37 out.println( "</body>" );
38
39 // end XHTML document
40 out.println( "</html>" );
41 out.close(); // close stream to complete the page
42 }
43 }
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
WelcomeServlet.
5 <!-- Fig. 24.6: WelcomeServlet.html --> html
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Handling an HTTP Get Request</title>
10 </head>
11
12 <body>
13 <form action = "/jhtp5/welcome1" method = "get">
14
15 <p><label>Click the button to invoke the servlet
16 <input type = "submit" value = "Get HTML Document" />
17 </label></p>
18
19 </form>
20 </body>
21 </html>
Program output
24.3.1 Setting Up the Apache Tomcat Server

• Download Tomcat (version 4.1.12)


– jakarta.apache.org/builds/
jakarta-tomcat-4.0/release/v4.1.12/bin/
• Define environment variables
– JAVA_HOME
– CATALINA_HOME
• Start the Tomcat server
– startup.bat
• Connect to the Tomcat server using a Web
browser
– http://localhost:8080/
24.3.1 Setting Up the Apache Tomcat Server
(Cont.).

Fig. 24.7 Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)
24.3.2 Deploying a Web Application

• Web applications
– JSPs, servlets and their supporting files
• Deploying a Web application
– Directory structure
• Context root
– Web application archive file (WAR file)
– Deployment descriptor
• web.xml
24.3.2 Deploying a Web Application (Cont.)

Directory Description
context root This is the root directory for the Web application. All the
JSPs, HTML documents, servlets and supporting files such
as images and class files reside in this directory or its
subdirectories. The name of this directory is specified by the
Web application creator. To provide structure in a Web
application, subdirectories can be placed in the context root.
For example, if your application uses many images, you
might place an images subdirectory in this directory. The
examples of this chapter use jhtp5 as the context root.
WEB-INF This directory contains the Web application deployment
descriptor (web.xml).
WEB-INF/classes This directory contains the servlet class files and other
supporting class files used in a Web application. If the
classes are part of a package, the complete package directory
structure would begin here.
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR
files can contain servlet class files and other supporting class
files used in a Web application.
Fig. 24.8 Web application standard directories.
1 <!DOCTYPE web-app PUBLIC \
2 "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
3 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
4
5 <web-app>
6
7 <!-- General description of your Web application -->
8 <display-name>
9 Java How to Program JSP
10 and Servlet Chapter Examples
11 </display-name>
12
13 <description>
14 This is the Web application in which we
15 demonstrate our JSP and Servlet examples.
16 </description>
17
18 <!-- Servlet definitions -->
19 <servlet>
20 <servlet-name>welcome1</servlet-name>
21
22 <description>
23 A simple servlet that handles an HTTP get request.
24 </description>
25
26 <servlet-class>
27 WelcomeServlet
28 </servlet-class>
29 </servlet>
30
31 <!-- Servlet mappings -->
32 <servlet-mapping>
33 <servlet-name>welcome1</servlet-name>
34 <url-pattern>/welcome1</url-pattern>
35 </servlet-mapping>
36
37 </web-app>
24.3.2 Deploying a Web Application (Cont.)

• Invoke WelcomeServlet example


– /jhtp5/welcome1
• /jhtp5 specifies the context root
• /welcome1 specifies the URL pattern
• URL pattern formats
– Exact match
• /jhtp5/welcome1
– Path mappings
• /jhtp5/example/*
– Extension mappings
• *.jsp
– Default servlet
• /
24.3.2 Deploying a Web Application (Cont.)

WelcomeServlet Web application directory and file structure


jhtp5
servlets
WelcomeServlet.html
WEB-INF
web.xml
classes
WelcomeServlet.class
Fig. 24.10 Web application directory and file structure for
WelcomeServlet.
24.4 Handling HTTP get Requests Containing
Data
• Servlet WelcomeServlet2
– Responds to a get request that contains data
1 // Fig. 24.11: WelcomeServlet2.java
2 // Processing HTTP get requests containing data.
3
4 import javax.servlet.*;
WelcomeServlet2
responds to a
5 import javax.servlet.http.*;
get request
6 import java.io.*;
that contains
7
data.
8 public class WelcomeServlet2 extends HttpServlet {
9 Line 15
10 // process "get" request from client
11 protected void doGet( HttpServletRequest request,
12 HttpServletResponse response )
13 throws ServletException, IOException
14 {
15 String firstName =
request.getParameter( "firstname" );
16
17 response.setContentType( "text/html" );
18 PrintWriter out = response.getWriter();
19
20 // send XHTML document to client
21
22 // start XHTML document
23 out.println( "<?xml version = \"1.0\"?>" );
24
25 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD "
+
26 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
27 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
WelcomeServlet2
responds to a
28
get request
29 out.println( "<html xmlns =
\"http://www.w3.org/1999/xhtml\">" );
that contains
data.
30
31 // head section of document
Line 39
32 out.println( "<head>" );
33 out.println(
34 "<title>Processing get requests with
data</title>" );
35 out.println( "</head>" );
36
37 // body section of document
38 out.println( "<body>" );
39 out.println( "<h1>Hello " + firstName + ",<br />" );
40 out.println( "Welcome to Servlets!</h1>" );
41 out.println( "</body>" );
42
43 // end XHTML document
44 out.println( "</html>" );
45 out.close(); // close stream to complete the page
46 }
47 }
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 HTML document
5 <!-- Fig. 24.12: WelcomeServlet2.html -->
in which the
form’s action
6
invokes
7 <html xmlns = "http://www.w3.org/1999/xhtml">
WelcomeServlet2
8 <head>
through the
9 <title>Processing get requests with data</title>
alias welcome2
10 </head> specified in
11 web.xml.
12 <body>
13 <form action = "/jhtp5/welcome2" method = "get"> Line 17
14
15 <p><label>
16 Type your first name and press the Submit button
17 <br /><input type = "text" name = "firstname" />
18 <input type = "submit" value = "Submit" />
19 </p></label>
20
21 </form>
22 </body>
23 </html>
HTML document
in which the
form’s action
invokes
WelcomeServlet2
through the
alias welcome2
specified in
web.xml.

Program output
24.4 Handling HTTP get Requests Containing
Data (Cont.)
Descriptor element Value
servlet element
servlet-name welcome2
description Handling HTTP get requests with data.
servlet-class WelcomeServlet2
servlet-
mapping element
servlet-name welcome2
url-pattern /welcome2
Fig. 24.13 Deployment descriptor information for servlet
WelcomeServlet2.
24.5 Handling HTTP post Requests

• HTTP post request


– Post data from an HTML form to a server-side form handler
– Browsers cache Web pages
• Servlet WelcomeServlet3
– Responds to a post request that contains data
1 // Fig. 24.14: WelcomeServlet3.java
2 // Processing post requests containing data.
3
4 import javax.servlet.*; WelcomeServlet3
5 import javax.servlet.http.*; responds to a
6 import java.io.*; post request
7
that contains
8 public class WelcomeServlet3 extends HttpServlet {
data.
9
10 // process "post" request from client
11 protected void doPost( HttpServletRequest request,
Declare a doPost
Linesmethod
11-46
12 HttpServletResponse response ) to responds to post requests.
13 throws ServletException, IOException
14 {
15 String firstName = request.getParameter( "firstname" );
16
17 response.setContentType( "text/html" );
18 PrintWriter out = response.getWriter();
19
20 // send XHTML page to client
21
22 // start XHTML document
23 out.println( "<?xml version = \"1.0\"?>" );
24
25 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
26 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
27 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
28 WelcomeServlet3
29 out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
30
.java
31 // head section of document
32 out.println( "<head>" );
33 out.println(
34 "<title>Processing post requests with data</title>" );
35 out.println( "</head>" );
36
37 // body section of document
38 out.println( "<body>" );
39 out.println( "<h1>Hello " + firstName + ",<br />" );
40 out.println( "Welcome to Servlets!</h1>" );
41 out.println( "</body>" );
42
43 // end XHTML document
44 out.println( "</html>" );
45 out.close(); // close stream to complete the page
46 }
47 }
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 HTML document
5 <!-- Fig. 24.15: WelcomeServlet3.html --> in which the
6 form’s action
7 <html xmlns = "http://www.w3.org/1999/xhtml"> invokes
8 <head>
WelcomeServlet3
9 <title>Handling an HTTP Post Request with Data</title>
through the
10 </head>
11
alias welcome3
12 <body> specified in
13 <form action = "/jhtp5/welcome3" method = "post">
Provide a form in which the
web.xml.
14 user can input a name in the
15 <p><label> text input element
Lines 13-21
16 Type your first name and press the Submit button firstname, then click the
17 <br /><input type = "text" name = "firstname" /> Submit button to invoke
18 <input type = "submit" value = "Submit" /> WelcomeServlet3.
19 </label></p>
20
21 </form>
22 </body>
23 </html>
HTML document
in which the
form’s action
invokes
WelcomeServlet3
through the
alias welcome3
specified in
web.xml.

Program output
24.5 Handling HTTP post Requests (Cont.)

Descriptor Value
element
servlet element
servlet-name welcome3
description Handling HTTP post requests with
data.
servlet-class WelcomeServlet3
servlet-
mapping element
servlet-name welcome3
url-pattern /welcome3
Fig. 24.16 Deployment descriptor information for servlet
WelcomeServlet3.
24.6 Redirecting Requests to Other Resources

• Servlet RedirectServlet
– Redirects the request to a different resource
1 // Fig. 24.17: RedirectServlet.java
2 // Redirecting a user to a different Web page.
3
4 import javax.servlet.*;
RedirectServlet
5 import javax.servlet.http.*;
redirecting
6 import java.io.*;
7
requests to
8 public class RedirectServlet extends HttpServlet { other
9 resources.
10 // process "get" request from client
11 protected void doGet( HttpServletRequest request, Line 15
12 HttpServletResponse response )
13 throws ServletException, IOException
Obtains theLines
page 19-23
14 {
15 String location = request.getParameter( "page" );
parameter from the request.
Line 20
16
17 if ( location != null )
18 Determine if the valueLine
is either
23
19 if ( location.equals( "deitel" ) ) “deitel” or “welcome1”
20 response.sendRedirect( "http://www.deitel.com" ); Lines 29-56
21 else Redirects the request to
22 if ( location.equals( "welcome1" ) ) www.deitel.com.
23 response.sendRedirect( "welcome1" );
24 Redirects the request to the
servlet WelcomeServlet.
25 // code that executes only if this servlet
26 // does not redirect the user to another page
27
Output a Web page indicating that an
28
invalid request wasRedirectServlet
response.setContentType( "text/html" );
29 PrintWriter out = response.getWriter();
made if method
redirecting
sendRedirect is not called.
30
requests to
31 // start XHTML document
other
32 out.println( "<?xml version = \"1.0\"?>" );
33
resources.
34 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
35 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" + Lines 28-55
36 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
37
38 out.println(
39 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
40
41 // head section of document
42 out.println( "<head>" );
43 out.println( "<title>Invalid page</title>" );
44 out.println( "</head>" );
45
46 // body section of document
47 out.println( "<body>" );
48 out.println( "<h1>Invalid page requested</h1>" );
49 out.println( "<p><a href = " +
50 "\"servlets/RedirectServlet.html\">" );
51 out.println( "Click here to choose again</a></p>" );
52 out.println( "</body>" ); RedirectServlet
53
redirecting
54 // end XHTML document
requests to
55 out.println( "</html>" );
56 out.close(); // close stream to complete the page
other
57 } resources.
58 }
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 RedirectServlet
5 <!-- Fig. 24.18: RedirectServlet.html --> .html document
6 to demonstrate
7 <html xmlns = "http://www.w3.org/1999/xhtml"> redirecting
8 <head>
requests to
9 <title>Redirecting a Request to Another Site</title>
other
10 </head>
11
resources.
12 <body>
13 <p>Click a link to be redirected to the appropriate page</p> Lines 15-16
14 <p>
15 <a href = "/jhtp5/redirect?page=deitel"> Provide hyperlinks that allow
Lines 17-18
16 www.deitel.com</a><br /> the user to invoke the servlet
17 <a href = "/jhtp5/redirect?page=welcome1"> RedirectServlet.
18 Welcome servlet</a>
19 </p>
20 </body>
21 </html>n
RedirectServlet
.html document
to demonstrate
redirecting
requests to
other
resources.

Program output
24.6 Redirecting Requests to other Resources
(Cont.)
Descriptor Value
element
servlet
element
servlet- redirect
name
description Redirecting to static Web pages and other
servlets.
servlet- com.deitel.jhtp5.servlets.RedirectServlet
class
servlet-
mapping
element
servlet- redirect
name
url-pattern /redirect
Fig. 24.19 Deployment descriptor information for servlet
RedirectServlet.
State Management using Hidden Form

A hidden (invisible) textfield is used for


maintaining the state of a user.
In such case, we store the information in the hidden
field and get it from another servlet. This approach is
better if we have to submit form in all the pages and
we don't want to depend on the browser.
State Management using Hidden Form

Let's see the code to store value in hidden field.

1.<input type="hidden" name="uname" value=“Huda


Almustafa">

Here, uname is the hidden field name and Huda Almustafa is the
hidden field value
State Management using Hidden Form

Let's see the code to store value in hidden field.

1.<input type="hidden" name="uname" value=“Huda


Almustafa">

Here, uname is the hidden field name and Huda Almustafa is the
hidden field value
State Management using Hidden Form

Real application of hidden form field


It is widely used in comment form of a website. In
such case, we store page id or page name in the
hidden field so that each page can be uniquely
identified.

Advantage of Hidden Form Field


1.It will always work whether cookie is disabled or
not.
Disadvantage of Hidden Form Field:
1.It is maintained at server side.
2.Extra form submission is required on each pages.
3.Only textual information can be used.
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value=‘ "+n+“ ‘ >");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletR
esponse response)

response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.println("Hello "+n);

}
}
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>
Events and listeners
• Events are basically occurrence of something.

• An event can be a change in the state in a life cycle of an


object.

• When the ServletContext object is created and


destroyed, or when an attribute (a key/value pair) is
created, removed, or replaced, we can say these moments
as events which we can listen to.

• Servlet Listener is used for listening to these events

• The servlet container generates events that trigger the


action of event listener classes
ServletContext object is created by the servlet container when
it initializes, we can therefore utilize this event:

• counting total and current logged-in users


• Loading a JDBC driver or creating a database connection
object.
• Load a file and save it in a variable in the ServletContext
object so that it is accessible from all the servlets
in the web application.
• notify users when attributes change and if sessions or
servlet contexts are created or destroyed.

When ServletContext object is destroyed

• Write cleanup code like closing files or closing a


database connection.
Servlet States
There are three states of a servlet: new, ready and end

•The servlet is in new state if servlet instance is created


(only once)

•After invoking the init() method used to initialize the


servlet (only once) Servlet comes in the ready state.

•In the ready state service method is invoked (each time


with request) servlet performs all the tasks.

•When the web container invokes the destroy() method, it


shifts to the end state.
Listeners

• Servlet context listeners manage resources at an application


level.

• Session listeners manage resources that are associated with a


series of requests from a single client.

• Listener is a class that implements the javax listener


interface
Listener Interfaces Event Classes

ServletRequestListener ServletRequestEvent
ServletRequestAttributeListener ServletContextEvent
ServletContextListener ServletRequestAttributeEvent
ServletContextAttributeListener ServletContextAttributeEvent
HttpSessionListener HttpSessionEvent
HttpSessionAttributeListener HttpSessionBindingEvent
HttpSessionBindingListener
HttpSessionActivationListener
ServletContextEvent and
ServletContextListener

The ServletContextEvent is notified when web application is


deployed on the server. And is created by the web container.

If you want to perform some action at the time of deploying the


web application such as creating database connection, creating all
the tables of the project etc, you need to implement
ServletContextListener interface and provide the implementation
of its methods.
Method of ServletContextEvent
class

There is only one method defined in the


ServletContextEvent class:

• public ServletContext getServletContext();


returns the instance of ServletContext.
Methods of ServletContextListener
interface
•javax.servlet.ServletContextListener interface:

•Has two methods:

•void contextInitialized(ServletContextEvent)
is invoked when application is deployed on the
server.

•void contextDestroyed(ServletContextEvent)
is invoked when application is undeployed from
the server.
1.In this example, we are creating table of the project. So we
don't need to create all the tables manually in the database.
import javax.servlet.*;
import java.sql.*;

public class MyListener implements ServletContextListener{

public void contextInitialized(ServletContextEvent arg0) {

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

String query="create table emp32(id number(10),name varchar2(40))";


PreparedStatement ps=con.prepareStatement(query);
ps.executeUpdate();

System.out.println(query);

public void contextDestroyed(ServletContextEvent arg0) {


System.out.println("project undeployed");

}
}
Filters

A filter is an object that is invoked at the preprocessing


and postprocessing of a request.

It is mainly used to perform filtering tasks such as


conversion, logging, compression, encryption and
decryption, input validation etc.

The servlet filter is pluggable, i.e. its entry is defined in


the web.xml file, if we remove the entry of filter from the
web.xml file, filter will be removed automatically and we
don't need to change the servlet.
So maintenance cost will be less.
<a href="servlet1">click here</a>

1.import java.io.IOException;
2.import java.io.PrintWriter;
3.
4.import javax.servlet.*;
5.
6.public class MyFilter implements Filter{
7.
8.public void init(FilterConfig arg0) throws ServletException {}
9.
10.public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=resp.getWriter();
14. out.print("filter is invoked before");
15.
16. chain.doFilter(req, resp);//sends request to next resource
17.
18. out.print("filter is invoked after");
19. }
20. public void destroy() {}
21.}
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpSer
vletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("<br>welcome to servlet<br>");

}
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>

</web-app>
24.7 Multi-Tier Applications

• Three-tier distributed applications


– User interface
– Business logic
– Database access
• Web servers often represent the middle tier
Connect Servlet to the Database
• Make sure you have java4s table in the database
with some data in it
• Make sure you have ojdbc14.jar file in your
classpath and lib folder as well
• Servlet will use ojdbc14.jar file which is in the
classpath, for compiling the application, and
ojdbc14.jar file in lib folder will be used at the
time of running the servlet application
Connect Servlet to the Database
Files Required
• index.html
• ServletDatabaseConnect.java
• web.xml
• ojdbc14.jar
Index.html

<form action="show" method="post">


Enter Table Name :
<input type="text" name="table">
<input type="submit" value="Display">
</font>
</form>
ServletDatabaseConnect.java
public class ServletDatabaseConnect extends HttpServlet
{
protected void doPost(HttpServletRequest req,HttpServletResponse
res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String tb=req.getParameter("table");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"admin");

Statement st=con.createStatement();

System.out.println("connection established successfully...!!");


ResultSet rs=st.executeQuery("Select * from "+tb);
pw.println("<table border=1>");
while(rs.next())
{
pw.println("<tr><td>"+rs.getInt(1)+"</
td><td>"+rs.getString(2)+"</td>"+ "<td>"+rs.getString(3)+"</td></tr>");

}
pw.println("</table>");
pw.close();
}
catch (Exception e){
e.printStackTrace();

} }}
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8.
9. <h1>Add New Employee</h1>
10. <form action="SaveServlet" method="post">
11. <table>
12. <tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
13. <tr><td>Password:</td><td><input type="password" name="password"/></td></tr>
14. <tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
15. <tr><td>Country:</td><td>
16. <select name="country" style="width:150px">
17. <option>India</option>
18. <option>USA</option>
19. <option>UK</option>
20. <option>Other</option>
21. </select>
22. </td></tr>
23. <tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>
24. </table>
25. </form>
26.
27. <br/>
28. <a href="ViewServlet">view employees</a>
29.
30. </body>
31. </html>
1. public class Emp {
2. private int id;
3. private String name,password,email,country;
4. public int getId() {
5. return id;
6. }
7. public void setId(int id) {
8. this.id = id;
9. }
10. public String getName() {
11. return name;
12. }
13. public void setName(String name) {
14. this.name = name;
15. }
16. public String getPassword() {
17. return password;
18. }
19. public void setPassword(String password) {
20. this.password = password;
21. }
22. public String getEmail() {
23. return email;
24. }
25. public void setEmail(String email) {
26. this.email = email;
27. }
28. public String getCountry() {
29. return country;
30. }
31. public void setCountry(String country) {
32. this.country = country;
33. }
34.
35. }
1. import java.util.*;
2. import java.sql.*;
3.
4. public class EmpDao {
5.
6. public static Connection getConnection(){
7. Connection con=null;
8. try{
9. Class.forName("oracle.jdbc.driver.OracleDriver");
10. con=DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","system","oracle");
11. }catch(Exception e){System.out.println(e);}
12. return con;
13. }
14.
1. public static int save(Emp e){
2. int status=0;
3. try{
4. Connection con=EmpDao.getConnection();
5. PreparedStatement ps=con.prepareStatement(
6. "insert into user905(name,password,email,country) values (?,?,?,?)");
7. ps.setString(1,e.getName());
8. ps.setString(2,e.getPassword());
9. ps.setString(3,e.getEmail());
10. ps.setString(4,e.getCountry());
11.
12. status=ps.executeUpdate();
13.
14. con.close();
15. }catch(Exception ex){ex.printStackTrace();}
16.
17. return status;
18. }
1. public static int update(Emp e){
2. int status=0;
3. try{
4. Connection con=EmpDao.getConnection();
5. PreparedStatement ps=con.prepareStatement(
6. "update user905 set name=?,password=?,email=?,country=? whe
re id=?");
7. ps.setString(1,e.getName());
8. ps.setString(2,e.getPassword());
9. ps.setString(3,e.getEmail());
10. ps.setString(4,e.getCountry());
11. ps.setInt(5,e.getId());
12.
13. status=ps.executeUpdate();
14.
15. con.close();
16. }catch(Exception ex){ex.printStackTrace();}
17.
18. return status;
19. }
1. public static int delete(int id){
2. int status=0;
3. try{
4. Connection con=EmpDao.getConnection();
5. PreparedStatement ps=con.prepareStatement("delete from
user905 where id=?");
6. ps.setInt(1,id);
7. status=ps.executeUpdate();
8.
9. con.close();
10. }catch(Exception e){e.printStackTrace();}
11.
12. return status;
13. }
1. public static Emp getEmployeeById(int id){
2. Emp e=new Emp();
3.
4. try{
5. Connection con=EmpDao.getConnection();
6. PreparedStatement ps=con.prepareStatement("select * from user905 where id=?"
);
7. ps.setInt(1,id);
8. ResultSet rs=ps.executeQuery();
9. if(rs.next()){
10. e.setId(rs.getInt(1));
11. e.setName(rs.getString(2));
12. e.setPassword(rs.getString(3));
13. e.setEmail(rs.getString(4));
14. e.setCountry(rs.getString(5));
15. }
16. con.close();
17. }catch(Exception ex){ex.printStackTrace();}
18.
19. return e;
20. }
1. public static List<Emp> getAllEmployees(){
2. List<Emp> list=new ArrayList<Emp>();
3.
4. try{
5. Connection con=EmpDao.getConnection();
6. PreparedStatement ps=con.prepareStatement("select * from user905");
7. ResultSet rs=ps.executeQuery();
8. while(rs.next()){
9. Emp e=new Emp();
10. e.setId(rs.getInt(1));
11. e.setName(rs.getString(2));
12. e.setPassword(rs.getString(3));
13. e.setEmail(rs.getString(4));
14. e.setCountry(rs.getString(5));
15. list.add(e);
16. }
17. con.close();
18. }catch(Exception e){e.printStackTrace();}
19.
20. return list;
21. }
22. }
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.annotation.WebServlet;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. @WebServlet("/SaveServlet")
10. public class SaveServlet extends HttpServlet {
11. protected void doPost(HttpServletRequest request, HttpServletResponse respons
e)
12. throws ServletException, IOException {
13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15.
16. String name=request.getParameter("name");
17. String password=request.getParameter("password");
18. String email=request.getParameter("email");
19. String country=request.getParameter("country");
20.
1. Emp e=new Emp();
2. e.setName(name);
3. e.setPassword(password);
4. e.setEmail(email);
5. e.setCountry(country);
6.
7. int status=EmpDao.save(e);
8. if(status>0){
9. out.print("<p>Record saved successfully!</p>");
10. request.getRequestDispatcher("index.html").include(request, response);
11. }else{
12. out.println("Sorry! unable to save record");
13. }
14.
15. out.close();
16. }
17. }
1 // Fig. 24.20: SurveyServlet.java
2 // A Web-based survey that uses JDBC from a servlet.
3 package com.deitel.jhtp5.servlets;
4 SurveyServlet.j
5 import java.io.*; ava
6 import java.text.*;
Multi-tier Web-
7 import java.sql.*;
based survey
8 import javax.servlet.*;
9 import javax.servlet.http.*;
using XHTML,
10 servlets and
11 public class SurveyServlet extends HttpServlet { JDBC.
12 private Connection connection;
Servlets are initialized by
13 private Statement statement; Lines 16-38
14
overriding method init.
15 // set up database connection and create SQL statement Lines 20-21
16 public void init( ServletConfig config ) throws ServletException
17 {
Line 23
18 // attempt database connection and create Statements
19 try {
Specify database
Lineslocation
24-25
20 System.setProperty( "db2j.system.home",
21 config.getInitParameter( "databaseLocation" ) );
22 Loads
Linesthe27-31
23 Class.forName( config.getInitParameter( "databaseDriver" ) ); database driver.
24 connection = DriverManager.getConnection(
25 config.getInitParameter( "databaseName" ) ); Attempt to open a connection to
the animalsurvey database.
26
27 // create Statement to query database Create Statement to
28 statement = connection.createStatement();
query database.
29 } SurveyServlet.j
30 ava
31 // for any exception throw an UnavailableException to Multi-tier Web-
32 // indicate that the servlet is not currently available based survey
33 catch ( Exception exception ) {
using XHTML,
34 exception.printStackTrace();
servlets and
35 throw new UnavailableException(exception.getMessage());
36 }
JDBC.
37
38 } // end of init method Line 28
39
40 // process survey response
41 protected void doPost( HttpServletRequest request,
42 HttpServletResponse response )
43 throws ServletException, IOException
44 {
45 // set up response to client
46 response.setContentType( "text/html" );
47 PrintWriter out = response.getWriter();
48 DecimalFormat twoDigits = new DecimalFormat( "0.00" );
49
50 // start XHTML document
51 out.println( "<?xml version = \"1.0\"?>" );
52
53 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + SurveyServlet.j
54 "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
ava
55 "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
Multi-tier Web-
56
57 out.println(
based survey
58 "<html xmlns = \"http://www.w3.org/1999/xhtml\">" ); using XHTML,
59 servlets and
60 // head section of document JDBC.
61 out.println( "<head>" );
62 Lines 64-65
63 // read current survey response
64 int value = Obtain theLines
survey 72-73
65 Integer.parseInt( request.getParameter( "animal" ) ); response
66 String query;
Line 74
67
68 // attempt to process a vote and display current results
69 try {
70
71 // update total for current surevy response
72 query = "UPDATE surveyresults SET votes = votes + 1 " + Create query to update total
73 "WHERE id = " + value; for current survey response
74 statement.executeUpdate( query );
75 Execute query to update total
for current survey response
// get total of all survey responses Create query to get total of all
query = "SELECT sum( votes ) FROM surveyresults"; survey responses
ResultSet totalRS = statement.executeQuery( query );
Execute query to get total of
totalRS.next(); SurveyServlet.j
all survey responses
int total = totalRS.getInt( 1 ); ava
Multi-tier Web-
// get results Create query to
based get
survey
query = "SELECT surveyoption, votes, id FROM surveyresults " + survey results XHTML,
using
"ORDER BY id";
servlets and
ResultSet resultsRS = statement.executeQuery( query ); Execute query to get
JDBC.
out.println( "<title>Thank you!</title>" ); survey results
out.println( "</head>" );
Line 77
out.println( "<body>" );
out.println( "<p>Thank you for participating." ); Line 78
out.println( "<br />Results:</p><pre>" );
Lines 83-84
// process results
int votes;
Line 85
while ( resultsRS.next() ) {
out.print( resultsRS.getString( 1 ) );
out.print( ": " );
votes = resultsRS.getInt( 2 );
out.print( twoDigits.format(
( double ) votes / total * 100 ) );
out.print( "% responses: " );
out.println( votes );
}
105
106 resultsRS.close();
107
108 out.print( "Total responses: " ); SurveyServlet.j
109 out.print( total ); ava
110 Multi-tier Web-
111 // end XHTML document based survey
112 out.println( "</pre></body></html>" ); using XHTML,
113 out.close();
servlets and
114
JDBC.
115 } // end try
116
117 // if database exception occurs, return error page
118 catch ( SQLException sqlException ) {
119 sqlException.printStackTrace();
120 out.println( "<title>Error</title>" );
121 out.println( "</head>" );
122 out.println( "<body><p>Database error occurred. " );
123 out.println( "Try again later.</p></body></html>" );
124 out.close();
125 }
126
127 } // end of doPost method
128
Method destroy closes
129 // close SQL statements and database when servlet terminates
130 public void destroy()
Statement and
131 { database connection.
132 // attempt to close statements and database connection SurveyServlet.j
133 try { ava
134 statement.close(); Multi-tier Web-
135 connection.close(); based survey
136 } using XHTML,
137 servlets and
138 // handle database exceptions by returning error to client
JDBC.
139 catch ( SQLException sqlException ) {
140 sqlException.printStackTrace();
141 }
Lines 130-136
142 }
143
144 } // end class SurveyServlet
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 Survey.html
5 <!-- Fig. 24.21: Survey.html --> document that
6
allows users to
7 <html xmlns = "http://www.w3.org/1999/xhtml">
submit survey
8 <head>
9 <title>Survey</title>
responses to
10 </head> SurveyServlet.
11
12 <body>
13 <form method = "post" action = "/jhtp5/animalsurvey">
14
15 <p>What is your favorite pet?</p>
16
17 <p>
18 <input type = "radio" name = "animal"
19 value = "1" />Dog<br />
20 <input type = "radio" name = "animal" Survey.html
21 value = "2" />Cat<br /> document that
22 <input type = "radio" name = "animal"
allows users to
23 value = "3" />Bird<br />
submit survey
24 <input type = "radio" name = "animal"
25 value = "4" />Snake<br />
responses to
26 <input type = "radio" name = "animal" SurveyServlet.
27 value = "5" checked = "checked" />None
28 </p>
29
30 <p><input type = "submit" value = "Submit" /></p>
31
32 </form>
33 </body>
34 </html>
Survey.html
document that
allows users to
submit survey
responses to
SurveyServlet.
24.7 Multi-Tier Applications: Using JDBC from a
Servlet (Cont.)
Descriptor element Value
servlet element
servlet-name animalsurvey
description Connecting to a database from a
servlet.
servlet-class com.deitel.jhtp5.servlets.SurveyServlet
init-param
param-name databaseLocation
param-value C:/CloudScape_5.0
init-param
param-name databaseDriver
param-value com.ibm.db2j.jdbc.DB2jDriver
init-param
param-name databaseName
param-value jdbc:db2j:animalsurvey
servlet-mapping element
servlet-name animalsurvey
url-pattern /animalsurvey
Fig. 24.22 Deployment descriptor information for servlet SurveyServlet.

You might also like