0% found this document useful (0 votes)
5 views

Unit-5

Uploaded by

tmukthar518
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit-5

Uploaded by

tmukthar518
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

9Servlets are small programs that execute on the server

side of a Web connection

How Things work on Web?

9Client
-Web
Web browser (IE,
(IE Firefox)

9Server
-Web server (Tomcat, IIS)

9Protocoll
9P
-HTTP

9Language
-HTML
9As we are talking about web related stuff so, for us client
is our veryy own browsers

What does a web client do?

9Lets user request something

9Shows the result of the request

9You may consider server as a hardware machine or a


software application

What does a web sever do?

9It takes client’s request


9Gives something back to the client

Protocol

What does http do?

9It takes client request


q to server

9It brings server response to client

Language

What does HTML do?

9Gi
9Gives i
instructions
i to the
h browser
b
Lets put them together

9Browser is client side proxy who sends request

9Requestt is
9R i some kind
ki d off data
d t which
hi h is
i taken
t k by
b HTTP to
t
the server

9Web server is an Application who receives the request

9Server sends the response as an HTML

R
Request
t

9Request
q is browser's interaction with server
9Key elements of request stream
1.HTTP method
-Get
-Post
2 The page URL
2.The
3.Form parameters

Response

9Response is server reply to browser

9Key elements of response stream


1.Status code
-200
200 Ok
-404 Not Found
2.Content type
-Image
-HTML
3.Content

HTTP Request

9Every
Every request has a request line, request headers and
message body (in the case of post method)

9Form data can be sent to the server by using various


methods
Request methods
What method we'll be using?
9We mainlyy use
-GET
Every request is GET
Cli ki a link
Clicking li k
Typing URL in browser
-POST
POST
Send user data to the server
A Get Request
Anatomy of Get Request
Anatomy of Post Request
HTTP Response

9HTML is a part of HTTP response

9I has
9It h response headers
h d withi h the
h response content

9Content types are known as MIME


text/html
text/plain
p
Image/jpeg
text/xml
Anatomy of Response
Introduction to Servlets

9Consider dynamic content. Assume that an online store


uses a database to store information about its business

9This would include items for sale, prices, availability,


orders,
o de s, and
a d so forth
o

9It wishes to make this information accessible to customers


via Web pages

9 The
Th contents
t t off those
th W b pages mustt be
Web b dynamically
d i ll
generated in order to reflect the latest information in the
database
9In the early days of the Web, a server could dynamically
construct a ppage
g byy creatingg a separate
p pprocess to handle
each client request

9The process would open connections to one or more


databases in order to obtain the necessary information

9It communicated with the Web server via an interface


known as the Common Gateway Interface (CGI)

9CGI allowed the separate process to read data from the


HTTP request and write data to the HTTP response

9A variety
i off different
diff l
languages were usedd to build
b ild CGI
programs. These included C, C++, and Perl
9However, CGI suffered serious performance problems

9It was expensive in terms of processor and memory


resources to create a separate process for each client request

9It was also expensive to open and close database


connections
ti f eachh client
for li t requestt

9In
In addition,
addition the CGI programs were not platform
platform-
independent

9Therefore, other techniques were introduced. Among these


are servlets
Advantages of Servlets

9First, performance
9Fi f iis significantly
i ifi l better
b
-Servlets execute within the address space of a Web server
-It
It is not necessary to create a separate process to handle
each client request

9Second, servlets are platform-independent because they


are written in Java
-A number of Web servers from different vendors offer the
Servlet API

9Third, the Java security manager on the server enforces a


set of restrictions to protect the resources on a server

9The full functionality of the Java class libraries is


available to a servlet

9It can communicate with applets, databases, or other


software via the sockets and RMI mechanisms

Using Tomcat For Servlet Development


9Tomcat
Tomcat is an openopen-source
source product maintained by the
Jakarta Project of the Apache Software Foundation

9It contains the class libraries, documentation, and run-time


support that you will need to create and test servlets

Tomcat Installation
9Set JAVA_HOME environment Variable
9Set the environment variable for CATALINA_HOME as the
Tomcat’s directory. It is needed to start the Tomcat server
9Goto Tomacat.exe file

9Double click on exe file


9Choose the folder in which to install Apache Tomcat
9Provide Administrator user name and password
9Select the path of a jre installed on your system
9Apache Tomcat is being installed
9Apache Tomcat has been installed on your computer
9To stop the Tomcat server

9To start the Tomcat server


9Or You can start or stop the Tomcat server in the following way
9Set CLASSPATH environment variable
Building and testing a servlet

9Create Servlet Source Code

FirstServlet.java
j
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest
request,HttpServletResponse response)
throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
p ( );
out.println("<title>My First Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello! WELCOME to Servlets</h1>");
out.println("</body>");
t i tl ("</b d >")
out.println("</html>");
}
}
9Create firstservlet folder under C:\Program Files\Tomcat 6.0\
webapps

9Create src folder under C:\Program Files\Tomcat 6.0\ webapps\


firstservlet and place FirstServlet.java
FirstServlet java file
9Create WEB-INF folder under C:\Program Files\Tomcat 6.0\
webapps\firstservlet

9Create classes folder under C:\Program Files\ Tomcat 6.0\ webapps


\ firstservlet\WEB-INF
9Compile Servlet Source Code and place class file uner C:\Program
Files\ Tomcat 6.0\ webapps \ firstservlet\WEB-INF \classes

9Create web.xml
<web-app>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>FirstServlet</servlet-class>
l l Fi S l / l l
</servlet>
pp g
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
</web-app>
9Pl
9Place web.xml
b l under
d C \P
C:\Program Fil \T
Files\Tomcat
t 6.0\
6 0\ webapps\
b \
firstservlet\WEB-INF
9Start the Tomcat Server, and run the FirstServlet by typing
http://localhost:8080/firstservlet/First in the URL of the web browser

9Our fi
9O firstservlet
t l t
folder will look like
this
Life cycle of a servlet
9Three methods are central to the life cycle
y of a servlet

9These are init( ), service( ) and destroy( )

9User enters a Uniform Resource Locator (URL) to a Web


browser

9The browser then ggenerates an HTTP request


q for this URL

9This request is then sent to the appropriate server

9HTTP request is received by the Web server

9The server maps this request to a particular servlet


9The servlet is dynamically retrieved and loaded into the
address space of the server

9The server invokes the init( ) method of the servlet.This


method is invoked only when the servlet is first loaded into
memory. It is possible to pass initialization parameters to the
servlet so it may configure itself

9Next, the server invokes the service( ) method of the


servlet. This method is called to process the HTTP request.
Servlets can read the data provided by the HTTP request

9The servlet remains in the server’s address space and is


available to process any other HTTP requests received from
clients. The service( ) method is called for each HTTP
request
9Finally server unloads the servlet from the memory using
the destroy() method
Example (LifeCycle.java)
import javax.servlet.*;
import
p jjavax.servlet.http.*;
p ;
import java.io.*;
public class LifeCycle extends GenericServlet
{
public void init(ServletConfig config) throws ServletException
{
S
System.out.println("init");
i l ("i i ")
}
ppublic void service(ServletRequest
( q request,
q , ServletResponse
p
response)
throws ServletException, IOException
{
System.out.println("from service");
PrintWriter out = response.getWriter();
out.println("You are in service");
}
public void destroy()
{
Sys e .ou .p
System.out.println("destroy");
( des oy );
}
}
9Follow
9F ll th steps
the t which
hi h are described
d ib d in
i the
th firstservlet
fi t l t
example to execute this servlet
9If y
you tryy to shutdown the Tomcat server yyou will gget the
message “destroy”

Th Servlet
The S l t API
9Two packages contain the classes and interfaces that are
required to build servlets

9These are javax.servlet and javax.servlet.http. They


constitute the Servlet API
9They are not included in the Java Software Development
Kit. They come up with Tomcat server

The javax.servlet Package

9The javax.servlet package contains a number of interfaces


and classes that establish the framework in which servlets
operate

9The following table summarizes the core interfaces that


are provided in this package

9All servlets must implement Servlet interface or extend a


class that implements the interface
9The following table summarizes the core classes that are
provided in the javax.servlet package
The Servlet Interface
9All servlets must implement the Servlet interface. It
d l
declares th init(
the i it( ),
) service(
i ( ) andd destroy(
d t ( ) methods
th d that
th t are
called by the server during the life cycle of a servlet
9The methods defined by Servlet are shown in the
follwingTable
The ServletRequest Interface
9It enables a servlet to obtain information about a client
request

ServletRequest methods

The ServletResponse Interface


9It enables a servlet to formulate a response for a client
ServletResponse methods

The GenericServlet Class


9The GenericServlet class provides implementations of
the basic life cycle methods for a servlet

9GenericServlet implements
p the Servlet and ServletConfigg
interfaces
Reading Servlet Parameters
9The ServletRequest
q class includes methods that allow yyou
to read the names and values of parameters that are included
in a client request
Example
E l (PostParameters.html)
(P tP t ht l)
<html>
<body>
<center>
<form name="Form1"
method get
method="get"
action="http://localhost:8080/postparameters/Para">
<table>
<t >
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input
pu type=submit
ype sub vvalue="Submit">
ue Sub
</form>
</center>
</body>
</html>

(PostParametersServlet.java)
import java.io.*;
import
p jjava.util.*;;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet {
public void service(ServletRequest request,
request ServletResponse response)
throws ServletException, IOException {
// Get print writer.
P i tW it pw = response.getWriter();
PrintWriter tW it ()
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
(String)e nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
i tl ( l )
}
pw.close();
}
}
9Follow the steps which are described in the firstservlet
example
p and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (PostParameters.html) in a browser

3.Enter an employee name and phone number in the text


fi ld
fields
4.Submit the Web page. The browser will display a response
that is dynamically
y y ggenerated by
y the servlet
The javax.servlet.http Package
9This ppackage
g contains a number of interfaces and classes
that are commonly used by servlet developers

9Used
9U d to build
b ild servlets
l that
h workk with
i h HTTP requests andd
responses

9The following table summarizes the core interfaces that


are p
provided in this ppackage:
g
9The following table summarizes the core classes that are
provided in this p
p package.
g The most important
p of these is
HttpServlet

The HttpServletRequest Interface


9The HttpServletRequest interface is implemented by the
server. It enables
bl a servlet
l t to
t obtain
bt i information
i f ti about
b t a
client request
HttpServletRequest methods

The HttpServletResponse Interface


9The HttpServletResponse interface is implemented by the
server. It enables
bl a servlet
l t to
t formulate
f l t an HTTP response
to a client
HttpServletResponse methods

The HttpSession Interface


9The HttpSession interface is implemented by the server

9It enables
bl a servlet
l t to
t readd andd write
it the
th state
t t information
i f ti
that is associated with an HTTP session
HttpSession methods
The Cookie Class
9The Cookie class encapsulates a cookie. A cookie is stored
on a client and contains state information

9Cookies are valuable for tracking user activities

9For example, assume that a user visits an online store. A


cookie can save the user’s name, address, and other
information. The user does not need to enter this data each
time he or she visits the store
9A servlet can write a cookie to a user’s machine via the
addCookie(( ) method of the HttpServletResponse
p p interface.
The data for that cookie is then included in the header of the
HTTP response that is sent to the browser

9The names and values of cookies are stored on the user’s


machine.
hi S
Some off the
th information
i f ti that
th t is
i savedd for
f eachh
cookie includes the following:

■ The name of the cookie


■ The value of the cookie
■ The expiration date of the cookie
■ The domain and path of the cookie
Cookie methods

The HttpServlet Class


9The HttpServlet class extends GenericServlet. It is
commonlyl usedd when
h developing
d l i servlets
l t that
th t receive
i andd
process HTTP requests
HttpServlet methods

Handling HTTP Requests and Responses

9The HttpServlet class provides specialized methods that


handle the various types of HTTP requests

9The GET and POST requests are commonly used when


handling form input
Handling HTTP GET Requests
9Here we will develop a servlet that handles an HTTP GET
request
<html> (ColorGet.html)
<body>
<center>
<form name="Form1"
action="
ti " http://localhost:8080
htt //l lh t 8080 /colorgetservlet
/ l t l t /Color">
/C l ">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value
value="Blue">Blue</option>
Blue >Blue</option>
</select>
<br><br>
<i t type=submit
<input t b it value="Submit">
l "S b it">
</form>
</center> </body></html>
(ColorGetServlet.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicc class
pub c ss Co
ColorGetServlet
o Ge Se v e eextends
e ds HttpServlet
pSe v e {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,
ServletException IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
p p
pw.println(color);
( );
pw.close();
}
}
9Follow the steps which are described in the firstservlet
example and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (ColorGet.html) in a browser

3.Select a color
4.Submit the Web page. The browser will display the
response that is dynamically generated by the servlet
9Parameters for an HTTP GET request are included as part
of the URL that is sent to the Web server

9The characters to the right of the question mark are known


as the
h query string
i
Handling HTTP POST Requests
9Here
Here we will develop a servlet that handles an HTTP
POST request
<html> (ColorPost.html)
<body>
<center>
<form name="Form1" "/ l
"/colorpostservlet/Cpost"
t l t/C t"
method="post"
action="http://localhost:8080/colorpostservlet/Cpost">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</center>
</body>
/body
</html>
(ColorPostServlet.java)
import java.io.*;
java io *;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
p
response) )
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.c ose();
pw.close();
}
}
9Follow
9F ll th steps
the t which
hi h are described
d ib d in
i the
th firstservlet
fi t l t
example and then
1 Start Tomcat (if it is not already running)
1.Start
2.Display the Web page (ColorPost.html) in a browser
3.Select a color

4.Submit the Web page. The browser will display the


response that is dynamically generated by the servlet
9Parameters for an HTTP POST request are not included as
part of the URL that is sent to the Web server

9The parameter names and values are sent in the body of


the
h HTTP request

Usingg Cookies
9Let’s develop a servlet that illustrates how to use cookies
(AddCookie.html)
<ht l>
<html>
<body>
<center>
<form name="Form1"
method="post"
action http://localhost:8080/addcookie/Add
action="http://localhost:8080/addcookie/Add">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</center>
/
</body>
</html>
(AddCookieServlet.java)
import java.io.*;
import javax.servlet.
javax servlet *;;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public
bli void id doPost(HttpServletRequest
d P (H S l R request, HttpServletResponse
H S l R
response) throws ServletException, IOException {
// Get pparameter from HTTP request.
q
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie(
Cookie("MyCookie"
MyCookie , data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
C T (" /h l")
PrintWriter pw = response.getWriter();
ppw.println("<B>MyCookie
p ( y has been set to");
);
pw.println(data);
pw.close();
}
}
(GetCookiesServlet.java)
i
import j
java.io.*;
i *
import javax.servlet.*;
import
p jjavax.servlet.http.*;
p
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException,
ServletException IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
tC t tT ("t t/ht l")
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
cookies[i] getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}
}
(Web.xml)
web app
<web-app>
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>AddCookieServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>gcs</servlet-name>
<servlet-class>GetCookiesServlet</servlet-class>
se v e c ss Ge Coo esSe v e /se v e c ss
</servlet>
<servlet-mapping>
<servlet name>add</servlet name>
<servlet-name>add</servlet-name>
<url-pattern>/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>gcs</servlet-name>
<url-pattern>/Getcs</url-pattern>
p p
</servlet-mapping>
</web-app>
9Follow the steps which are described in the firstservlet
example
p and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (AddCookie.html) in a browser

3.Enter a value for MyCookie


4.Submit the Web page

5.Next, request the following URL via the browser:


http://localhost:8080/addcookie/Getcs Alias of GetCookiesServlet
Session Tracking
9HTTP is a stateless protocol. Each request is independent
of the previous one

9In
In some applications, it is necessary to save state
information so that information can be collected from
several interactions between a browser and a server

9Sessions provide such mechanism

9The following servlet (DateServlet.java) illustrates how to


use session state
import java.io.*;
import java.util.*;
i
importt javax.servlet.*;
j l t*
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Get the HttpSession object.
object
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
( /h l )
PrintWriter pw = response.getWriter();
p p (
pw.print("<B>"); );
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display
Di l current date/time.
d /i
date = new Date();
(
hs.setAttribute("date",, date);
);
pw.println("Current date: " + date);
}}
9Follow the steps which are described in the firstservlet
example
p and then
1.Start Tomcat (if it is not already running)

2.When you first request this servlet, the browser displays


one line with the current date and time information

3.On subsequent invocations, two lines are displayed. The


first line shows the date and time when the servlet was last
accessed. The second line shows the current date and time

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy