SlideShare a Scribd company logo
01/30/15 Distributed Computing, M. L. Liu 1
Java Servlets
M. L. Liu
01/30/15 Distributed Computing, M. L. Liu2
Introduction
Servlets are modules that extend request/response-
oriented servers, such as Java-enabled web servers.
Servlets are to servers what applets are to browsers: an
external program invoked at runtime.
Unlike applets, however, servlets have no graphical
user interface.
Servlets can be embedded in many different servers
because the servlet API, which you use to write
servlets, assumes nothing about the server's
environment or protocol.
Servlets are portable.
01/30/15 Distributed Computing, M. L. Liu3
Servlet Basics
A servlet is an object of the javax.servlet class.
It runs inside a Java Virtual Machine on a server host.
Unlike applets, servlets do not require special support
in the web browser.
The Servlet class is not part of the Java Development
Kit (JDK). You must download the JDSK (Java
Servlet Development Kit).
A servlet is an object. It is loaded and runs in an object
called a servlet engine, or a servlet container.
01/30/15 Distributed Computing, M. L. Liu4
Uses for Servlets
http://java.sun.com/docs/books/tutorial/servlets/overview/index.html
Providing the functionalities of CGI scripts with a better
API and enhanced capabilities.
Allowing collaboration between people. A servlet can handle
multiple requests concurrently, and can synchronize
requests. This allows servlets to support systems such as on-
line conferencing.
Forwarding requests. Servlets can forward requests to other
servers and servlets. Thus servlets can be used to balance
load among several servers that mirror the same content,
and to partition a single logical service over several servers,
according to task type or organizational boundaries.
01/30/15 Distributed Computing, M. L. Liu5
Generic Servlets and HTTP Servlets
Java Servlet Programming, O’Reilley Press
Every servlet must implement the javax.servlet.Servlet
interface
Most servlets implement the interface by extending
one of these classes
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
A generic servlet should override the service( ) method
to process requests and generate appropriate responses.
An HTTP servlet overrides the doPost( ) and/or doGet(
) method.
01/30/15 Distributed Computing, M. L. Liu6
Generic and HTTP Servlets
G e n e r ic S e r v le t
s e r v ic e ( )
S e r v e r
C lie n t
r e q u e s t
r e s p o n s e
H T T P S e r v le t
s e r v ic e ( )
H T T P S e r v e r
B r o w s e r
r e q u e s t
r e s p o n s e
d o G e t ( )
d o P o s t ( )
01/30/15 Distributed Computing, M. L. Liu7
A simple Servlet, from
http://java.sun.com/docs/books/tutorial/servlets/overview/simple.html
public class SimpleServlet extends HttpServlet {
/** * Handle the HTTP GET method by building a simple web page. */
public void doGet (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out;
String title = "Simple Servlet Output";
// set content type and other response header fields first
response.setContentType("text/html");
// then write the data of the response out = response.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println(title);
out.println("</TITLE></HEAD><BODY>");
out.println("<H1>" + title + "</H1>");
out.println("<P>This is output from SimpleServlet.");
out.println("</BODY></HTML>");
out.close();
}
}
01/30/15 Distributed Computing, M. L. Liu8
Using HTTP Servlet to process web forms
http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html
Requests and Responses
Methods in the HttpServlet class that handle
client requests take two arguments:
An HttpServletRequest object, which
encapsulates the data from the client
An HttpServletResponse object, which
encapsulates the response to the client
public void doGet (HttpServletRequest request,
HttpServletResponse response)
public void doPost(HttpServletRequest request,
HttpServletResponse response)
01/30/15 Distributed Computing, M. L. Liu9
HttpServletRequest Objects
http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html
An HttpServletRequest object provides access to HTTP header
data, such as any cookies found in the request and the HTTP
method with which the request was made.
The HttpServletRequest object also allows you to obtain
the arguments that the client sent as part of the request.
To access client data:
The getParameter method returns the value of a named
parameter. If your parameter could have more than one value, use
getParameterValues instead. The getParameterValues
method returns an array of values for the named parameter. (The
method getParameterNames provides the names of the
parameters.)
For HTTP GET requests, the getQueryString method returns a
String of raw data from the client. You must parse this data
yourself to obtain the parameters and values.
01/30/15 Distributed Computing, M. L. Liu10
HttpServletRequest Interface
public String ServletRequest.getQueryString( ); returns the query string of
the requst.
public String GetParameter(String name): given the name of a parameter in
the query string of the request, this method returns the value.
String id = GetParameter(“id”)
public String[ ] GetParameterValues(String name): returns multiple values
for the named parameter – use for parameters which may have multiple
values, such as from checkboxes.
String[ ] colors = req.getParmeterValues(“color”);
if (colors != null)
for (int I = 0; I < colors.length; I++ )
out.println(colors[I]);
public Enumeration getParameterNames( ): returns an enumeration object
with a list of all of the parameter names in the query string of the request.
01/30/15 Distributed Computing, M. L. Liu11
HttpServletResponse Objects
http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html
An HttpServletResponse object provides two
ways of returning data to the user:
The getWriter method returns a Writer
The getOutputStream method returns a
ServletOutputStream
Use the getWriter method to return text data to the
user, and the getOutputStream method for binary
data.
Closing the Writer or ServletOutputStream after
you send the response allows the server to know when
the response is complete.
01/30/15 Distributed Computing, M. L. Liu12
HttpServletResponse Interface
public interface HttpServletResponse extends
ServletResponse: “The servlet engine provides an object
that implements this interface and passes it into th servlet
through the service method” – “Java Server Programming”
public void setContentType(String type) : this method must
be called to generate the first line of the HTTP response:
setContentType(“text/html”);
public PrintWriter getWriter( ) throws IOException:
returns an object which can be used for writing the
responses, one line at a time:
PrintWriter out = res.getWriter;
out.println(“<h1>Hello world</h1>”);
01/30/15 Distributed Computing, M. L. Liu13
Servlets are Concurrent servers
http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html
HTTP servlets are typically capable of serving
multiple clients concurrently.
If the methods in your servlet do work for
clients by accessing a shared resource, then you
must either:
Synchronize access to that resource, or
Create a servlet that handles only one client request
at a time.
01/30/15 Distributed Computing, M. L. Liu14
Handling GET requests
http://java.sun.com/docs/books/tutorial/servlets/client-interaction/http-
methods.html
public class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter(); 
// then write the response
out.println("<html>" +
"<head><title>Book Description</title></head>" + ...
); 
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
if (bookId != null) {
// fetch the information about the book and print it ...
} out.println("</body></html>");
01/30/15 Distributed Computing, M. L. Liu15
Handling POST Requests
http://java.sun.com/docs/books/tutorial/servlets/client-interaction/http-
methods.html
public class ReceiptServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter( );
// then write the response
out.println("<html>" + "<head><title> Receipt </title>"
+ ...);
out.println("Thank you for purchasing your books from us
" + request.getParameter("cardname") + ...);
out.close();
}
...
}
01/30/15 Distributed Computing, M. L. Liu16
The Life Cycle of an HTTP Servlet
The web server loads a servlet when it is called
for in a web page.
The web server invokes the init( ) method of
the servlet.
The servlet handles client responses.
The server destroys the servlet (at the request of
the system administrator). A servlet is
normally not destroyed once it is loaded.
01/30/15 Distributed Computing, M. L. Liu17
Servlet Examples
See Servletsimple folder in code sample:
HelloWorld.java: a simple servlet
Counter.java: illustrates that a servlet is persistent
Counter2.java: illustrates the use of synchronized
method with a servlet
GetForm.html, GetForm.java: illustrates the
processing of data sent with an HTTP request via the
GET method
PostForm.html, PostForm.java: illustrates the
processing of data sent with an HTTP request via the
POST method
01/30/15 Distributed Computing, M. L. Liu18
Session State Information
The mechanisms for state information
maintenance with CGI can also be used for
servlets: hidden-tag, URL suffix, file/database,
cookies.
In addition, a session tracking mechanism is
provided, using an HttpSession object.
01/30/15 Distributed Computing, M. L. Liu19
Cookies in Java
http://java.sun.com/products/servlet/2.2/javadoc/index.html
A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version
number. Some Web browsers have bugs in how they handle the optional
attributes, so use them sparingly to improve the interoperability of your
servlets.
The servlet sends cookies to the browser by using the
HttpServletResponse.addCookie(javax.servelet.http.Cookie) method,
which adds fields to HTTP response headers to send cookies to the
browser, one at a time. The browser is expected to support 20 cookies
for each Web server, 300 cookies total, and may limit cookie size to 4
KB each.
The browser returns cookies to the servlet by adding fields to HTTP
request headers. Cookies can be retrieved from a request by using the
HttpServletRequest.getCookies( ) method. Several cookies might have
the same name but different path attributes.
01/30/15 Distributed Computing, M. L. Liu20
Processing Cookies with Java
Java Server Programming – Wrox press
A cookie is an object of the javax.servlet.http.cookie class.
Methods to use with a cookie object:
public Cookie(String name, String value): creates a cookie
with the name-value pair in the arguments.
• import javax.servlet.http.*
• Cookie oreo = new Cookie(“id”,”12345”);
public string getName( ) : returns the name of the cookie
public string getValue( ) : returns the value of the cookie
public void setValue(String _val) : sets the value of the
cookie
public void setMaxAge(int expiry) : sets the
maximum age of the cookie in seconds.
01/30/15 Distributed Computing, M. L. Liu21
Processing Cookies with Java – 2
Java Server Programming – Wrox press
public void setPath(java.lang.String uri) : Specifies a path for
the cookie to which the client should return the cookie. The cookie is
visible to all the pages in the directory you specify, and all the pages in
that directory's subdirectories. A cookie's path must include the servlet
that set the cookie, for example, /catalog, which makes the cookie visible
to all directories on the server under /catalog.
public java.lang.String getPath() : Returns the path on the
server to which the browser returns this cookie. The cookie is visible to
all subpaths on the server.
public String getDomain( ) : returns the domain of the cookie.
• if orea.getDomain.equals(“.foo.com”)
• … // do something related to golf
public void setDomain(String _domain): sets the cookie’s domain.
01/30/15 Distributed Computing, M. L. Liu22
doGet Method using cookies
public void doGet(HttpServletResponse req, HttpServletResponse res)
throws ServletException, IOExceiption{
res.setContentType(“text/html”);
PrintWriter out = res.getWriter( );
out.println (“<H1>Contents of your shopping cart:</H1>”);
Cookie cookies[ ];
cookies = req.getCookies( );
if (cookies != null) {
for ( int i = 0; i < cookies.length; i++ ) {
if (cookies[i].getName( ).startWith(“Item”))
out.println( cookies[i].getName( ) + “: “ + cookies[i].getValue( ));
out.close( );
}
01/30/15 Distributed Computing, M. L. Liu23
Servlet & Cookies Example
See Servletcookies folder in code sample:
Cart.html: web page to allow selection of items
Cart.java: Servlet invoked by Cart.html; it instantiates
a cookie object for each items selected.
Cart2.html: web page to allow viewing of items
currently in cart
Cart2.java: Servlet to scan cookies received with the
HTTP request and display the contents of each cookie.
01/30/15 Distributed Computing, M. L. Liu24
HTTP Session Objects
http://java.sun.com/products/servlet/2.2/javadoc/index.html
The javax.servlet.http package provides a
public interface HttpSession: Provides a way to
identify a user across more than one page request or
visit to a Web site and to store information about that
user.
The servlet container uses this interface to create a
session between an HTTP client and an HTTP server.
The session persists for a specified time period, across
more than one connection or page request from the
user. A session usually corresponds to one user, who
may visit a site many times.
01/30/15 Distributed Computing, M. L. Liu25
HTTP Session Object - 2
http://java.sun.com/products/servlet/2.2/javadoc/index.html
This interface allows servlets to
View and manipulate information about a session, such as
the session identifier, creation time, and last accessed time
Bind objects to sessions, allowing user information to
persist across multiple user connections
Session object allows session state information to be
maintained without depending on the use of cookies
(which can be disabled by a browser user.)
Session information is scoped only to the current web
application (ServletContext), so information stored in
one context will not be directly visible in another.
01/30/15 Distributed Computing, M. L. Liu26
The Session object
A S e s s i o n o b j e c t
s e r v e l e t e n g i n e
w e b s e r v e r
S e r v e r h o s t
C l i e n t h o s t
r e q u e s t / r e s p o n s e
s e r v le t
01/30/15 Distributed Computing, M. L. Liu27
Obtaining an HTTPSession Object
• A session object is obtained using the getSession( ) method of the
HttpServletRequest object (from doPost or doGet)
• public HTTPSession getSession(boolean create):
Returns the current HttpSession associated with this request or,
if if there is no current session and create is true, returns a new
session. If create is false and the request has no valid
HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this
method before the response is committed.
public class ShoppingCart extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletRespnse res)
throws ServletException, IOException
…
// get session object
HttpSession session = req.getSession(true)
if (session != null) {
…
} …
01/30/15 Distributed Computing, M. L. Liu28
The HTTPSession Object methods
public java.lang.String getId( ): returns a string containing
the unique identifier assigned to this session. The identifier is
assigned by the servlet container and is implementation
dependent.
public java.lang.Object
getAttribute(java.lang.String name): returns the object
bound with the specified name in this session, or null if no
object is bound under the name.
public java.util.Enumeration getAttributeNames( ):
returns an Enumeration of String objects containing the names
of all the objects bound to this session.
public void removeAttribute(java.lang.String name):
removes the object bound with the specified name from this
session. If the session does not have an object bound with the
specified name, this method does nothing.
01/30/15 Distributed Computing, M. L. Liu29
Session Object example
See ServletSession folder in code sample:
Cart.html: web page to allow selection of items
Cart.java: Servlet invoked by Cart.html; it instantiates
a session object which contains descriptions of items
selected.
Cart2.html: web page to allow viewing of items
currently in cart
Cart2.java: Servlet to display items in the shopping
cart, as recorded by the use a session object in the Cart
servlet
01/30/15 Distributed Computing, M. L. Liu30
Summary - 1
A servlet is a Java class.
Its code is loaded to a servlet container on the
server host.
It is initiated by the server in response to a
client’s request.
Once loaded, a servlet is persistent.
01/30/15 Distributed Computing, M. L. Liu31
Summary - 2
For state information maintenance:
hidden form fields
cookies
the servlet’s instance variables may hold global data
a session object can be used to hold session data

More Related Content

What's hot

jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
jQuery
jQueryjQuery
HTML/CSS/java Script/Jquery
HTML/CSS/java Script/JqueryHTML/CSS/java Script/Jquery
HTML/CSS/java Script/Jquery
FAKHRUN NISHA
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
1amitgupta
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
Sahil Agarwal
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
Xcat Liu
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
jQuery
jQueryjQuery
jQuery
Vishwa Mohan
 
Servlets
ServletsServlets
Servlets
ZainabNoorGul
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
jQuery
jQueryjQuery

What's hot (20)

jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery
jQueryjQuery
jQuery
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
HTML/CSS/java Script/Jquery
HTML/CSS/java Script/JqueryHTML/CSS/java Script/Jquery
HTML/CSS/java Script/Jquery
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
jQuery
jQueryjQuery
jQuery
 
Servlets
ServletsServlets
Servlets
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
jQuery
jQueryjQuery
jQuery
 

Viewers also liked

Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
Лекция 2: АВЛ-деревья (AVL trees)
Лекция 2: АВЛ-деревья (AVL trees)Лекция 2: АВЛ-деревья (AVL trees)
Лекция 2: АВЛ-деревья (AVL trees)Mikhail Kurnosov
 
Chapter 4 2
Chapter 4 2Chapter 4 2
Chapter 4 2lopjuan
 
Chapter 3
Chapter 3Chapter 3
Chapter 3lopjuan
 
Лекция 5. B-деревья (B-trees, k-way merge sort)
Лекция 5. B-деревья (B-trees, k-way merge sort)Лекция 5. B-деревья (B-trees, k-way merge sort)
Лекция 5. B-деревья (B-trees, k-way merge sort)
Mikhail Kurnosov
 
Electronic payment system(EPS)
Electronic payment system(EPS)Electronic payment system(EPS)
Electronic payment system(EPS)rahul kundu
 
Core java course syllabus
Core java course syllabusCore java course syllabus
Core java course syllabus
Papitha Velumani
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
Danairat Thanabodithammachari
 
Commonly Used Image File Formats
Commonly Used Image File FormatsCommonly Used Image File Formats
Commonly Used Image File Formats
Fatih Özlü
 
MIS 10 Electronic Payment System
MIS 10 Electronic Payment SystemMIS 10 Electronic Payment System
MIS 10 Electronic Payment System
Tushar B Kute
 
Electronic payment system
Electronic payment systemElectronic payment system
Electronic payment systempankhadi
 
Image file formats
Image file formatsImage file formats
Image file formats
Bob Watson
 

Viewers also liked (13)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Лекция 2: АВЛ-деревья (AVL trees)
Лекция 2: АВЛ-деревья (AVL trees)Лекция 2: АВЛ-деревья (AVL trees)
Лекция 2: АВЛ-деревья (AVL trees)
 
Chapter 4 2
Chapter 4 2Chapter 4 2
Chapter 4 2
 
Servlets
ServletsServlets
Servlets
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Лекция 5. B-деревья (B-trees, k-way merge sort)
Лекция 5. B-деревья (B-trees, k-way merge sort)Лекция 5. B-деревья (B-trees, k-way merge sort)
Лекция 5. B-деревья (B-trees, k-way merge sort)
 
Electronic payment system(EPS)
Electronic payment system(EPS)Electronic payment system(EPS)
Electronic payment system(EPS)
 
Core java course syllabus
Core java course syllabusCore java course syllabus
Core java course syllabus
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
 
Commonly Used Image File Formats
Commonly Used Image File FormatsCommonly Used Image File Formats
Commonly Used Image File Formats
 
MIS 10 Electronic Payment System
MIS 10 Electronic Payment SystemMIS 10 Electronic Payment System
MIS 10 Electronic Payment System
 
Electronic payment system
Electronic payment systemElectronic payment system
Electronic payment system
 
Image file formats
Image file formatsImage file formats
Image file formats
 

Similar to Java servlets

Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
Hemo Chella
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
Payal Dungarwal
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T Spatinijava
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
gayathri.pptx
gayathri.pptxgayathri.pptx
gayathri.pptx
GayathriP95
 
Servlets
ServletsServlets
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and ServletsRaghu nath
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
megrhi haikel
 

Similar to Java servlets (20)

Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Servlet
Servlet Servlet
Servlet
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
gayathri.pptx
gayathri.pptxgayathri.pptx
gayathri.pptx
 
Servlets
ServletsServlets
Servlets
 
Weblogic
WeblogicWeblogic
Weblogic
 
Servlets
ServletsServlets
Servlets
 
Major project report
Major project reportMajor project report
Major project report
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 

More from lopjuan

Chapter 2
Chapter 2Chapter 2
Chapter 2lopjuan
 
Chapter 1
Chapter 1Chapter 1
Chapter 1lopjuan
 
Chapter 4 1
Chapter 4 1Chapter 4 1
Chapter 4 1lopjuan
 
Java applets
Java appletsJava applets
Java appletslopjuan
 
Chapter10
Chapter10Chapter10
Chapter10lopjuan
 
Web services
Web servicesWeb services
Web serviceslopjuan
 
Chapter7
Chapter7Chapter7
Chapter7lopjuan
 

More from lopjuan (7)

Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 4 1
Chapter 4 1Chapter 4 1
Chapter 4 1
 
Java applets
Java appletsJava applets
Java applets
 
Chapter10
Chapter10Chapter10
Chapter10
 
Web services
Web servicesWeb services
Web services
 
Chapter7
Chapter7Chapter7
Chapter7
 

Recently uploaded

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Java servlets

  • 1. 01/30/15 Distributed Computing, M. L. Liu 1 Java Servlets M. L. Liu
  • 2. 01/30/15 Distributed Computing, M. L. Liu2 Introduction Servlets are modules that extend request/response- oriented servers, such as Java-enabled web servers. Servlets are to servers what applets are to browsers: an external program invoked at runtime. Unlike applets, however, servlets have no graphical user interface. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol. Servlets are portable.
  • 3. 01/30/15 Distributed Computing, M. L. Liu3 Servlet Basics A servlet is an object of the javax.servlet class. It runs inside a Java Virtual Machine on a server host. Unlike applets, servlets do not require special support in the web browser. The Servlet class is not part of the Java Development Kit (JDK). You must download the JDSK (Java Servlet Development Kit). A servlet is an object. It is loaded and runs in an object called a servlet engine, or a servlet container.
  • 4. 01/30/15 Distributed Computing, M. L. Liu4 Uses for Servlets http://java.sun.com/docs/books/tutorial/servlets/overview/index.html Providing the functionalities of CGI scripts with a better API and enhanced capabilities. Allowing collaboration between people. A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on- line conferencing. Forwarding requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.
  • 5. 01/30/15 Distributed Computing, M. L. Liu5 Generic Servlets and HTTP Servlets Java Servlet Programming, O’Reilley Press Every servlet must implement the javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet javax.servlet.http.HttpServlet A generic servlet should override the service( ) method to process requests and generate appropriate responses. An HTTP servlet overrides the doPost( ) and/or doGet( ) method.
  • 6. 01/30/15 Distributed Computing, M. L. Liu6 Generic and HTTP Servlets G e n e r ic S e r v le t s e r v ic e ( ) S e r v e r C lie n t r e q u e s t r e s p o n s e H T T P S e r v le t s e r v ic e ( ) H T T P S e r v e r B r o w s e r r e q u e s t r e s p o n s e d o G e t ( ) d o P o s t ( )
  • 7. 01/30/15 Distributed Computing, M. L. Liu7 A simple Servlet, from http://java.sun.com/docs/books/tutorial/servlets/overview/simple.html public class SimpleServlet extends HttpServlet { /** * Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output"; // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); } }
  • 8. 01/30/15 Distributed Computing, M. L. Liu8 Using HTTP Servlet to process web forms http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html Requests and Responses Methods in the HttpServlet class that handle client requests take two arguments: An HttpServletRequest object, which encapsulates the data from the client An HttpServletResponse object, which encapsulates the response to the client public void doGet (HttpServletRequest request, HttpServletResponse response) public void doPost(HttpServletRequest request, HttpServletResponse response)
  • 9. 01/30/15 Distributed Computing, M. L. Liu9 HttpServletRequest Objects http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. The HttpServletRequest object also allows you to obtain the arguments that the client sent as part of the request. To access client data: The getParameter method returns the value of a named parameter. If your parameter could have more than one value, use getParameterValues instead. The getParameterValues method returns an array of values for the named parameter. (The method getParameterNames provides the names of the parameters.) For HTTP GET requests, the getQueryString method returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values.
  • 10. 01/30/15 Distributed Computing, M. L. Liu10 HttpServletRequest Interface public String ServletRequest.getQueryString( ); returns the query string of the requst. public String GetParameter(String name): given the name of a parameter in the query string of the request, this method returns the value. String id = GetParameter(“id”) public String[ ] GetParameterValues(String name): returns multiple values for the named parameter – use for parameters which may have multiple values, such as from checkboxes. String[ ] colors = req.getParmeterValues(“color”); if (colors != null) for (int I = 0; I < colors.length; I++ ) out.println(colors[I]); public Enumeration getParameterNames( ): returns an enumeration object with a list of all of the parameter names in the query string of the request.
  • 11. 01/30/15 Distributed Computing, M. L. Liu11 HttpServletResponse Objects http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html An HttpServletResponse object provides two ways of returning data to the user: The getWriter method returns a Writer The getOutputStream method returns a ServletOutputStream Use the getWriter method to return text data to the user, and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete.
  • 12. 01/30/15 Distributed Computing, M. L. Liu12 HttpServletResponse Interface public interface HttpServletResponse extends ServletResponse: “The servlet engine provides an object that implements this interface and passes it into th servlet through the service method” – “Java Server Programming” public void setContentType(String type) : this method must be called to generate the first line of the HTTP response: setContentType(“text/html”); public PrintWriter getWriter( ) throws IOException: returns an object which can be used for writing the responses, one line at a time: PrintWriter out = res.getWriter; out.println(“<h1>Hello world</h1>”);
  • 13. 01/30/15 Distributed Computing, M. L. Liu13 Servlets are Concurrent servers http://java.sun.com/docs/books/tutorial/servlets/client-interaction/req-res.html HTTP servlets are typically capable of serving multiple clients concurrently. If the methods in your servlet do work for clients by accessing a shared resource, then you must either: Synchronize access to that resource, or Create a servlet that handles only one client request at a time.
  • 14. 01/30/15 Distributed Computing, M. L. Liu14 Handling GET requests http://java.sun.com/docs/books/tutorial/servlets/client-interaction/http- methods.html public class BookDetailServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content-type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();  // then write the response out.println("<html>" + "<head><title>Book Description</title></head>" + ... );  //Get the identifier of the book to display String bookId = request.getParameter("bookId"); if (bookId != null) { // fetch the information about the book and print it ... } out.println("</body></html>");
  • 15. 01/30/15 Distributed Computing, M. L. Liu15 Handling POST Requests http://java.sun.com/docs/books/tutorial/servlets/client-interaction/http- methods.html public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter( ); // then write the response out.println("<html>" + "<head><title> Receipt </title>" + ...); out.println("Thank you for purchasing your books from us " + request.getParameter("cardname") + ...); out.close(); } ... }
  • 16. 01/30/15 Distributed Computing, M. L. Liu16 The Life Cycle of an HTTP Servlet The web server loads a servlet when it is called for in a web page. The web server invokes the init( ) method of the servlet. The servlet handles client responses. The server destroys the servlet (at the request of the system administrator). A servlet is normally not destroyed once it is loaded.
  • 17. 01/30/15 Distributed Computing, M. L. Liu17 Servlet Examples See Servletsimple folder in code sample: HelloWorld.java: a simple servlet Counter.java: illustrates that a servlet is persistent Counter2.java: illustrates the use of synchronized method with a servlet GetForm.html, GetForm.java: illustrates the processing of data sent with an HTTP request via the GET method PostForm.html, PostForm.java: illustrates the processing of data sent with an HTTP request via the POST method
  • 18. 01/30/15 Distributed Computing, M. L. Liu18 Session State Information The mechanisms for state information maintenance with CGI can also be used for servlets: hidden-tag, URL suffix, file/database, cookies. In addition, a session tracking mechanism is provided, using an HttpSession object.
  • 19. 01/30/15 Distributed Computing, M. L. Liu19 Cookies in Java http://java.sun.com/products/servlet/2.2/javadoc/index.html A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servelet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies( ) method. Several cookies might have the same name but different path attributes.
  • 20. 01/30/15 Distributed Computing, M. L. Liu20 Processing Cookies with Java Java Server Programming – Wrox press A cookie is an object of the javax.servlet.http.cookie class. Methods to use with a cookie object: public Cookie(String name, String value): creates a cookie with the name-value pair in the arguments. • import javax.servlet.http.* • Cookie oreo = new Cookie(“id”,”12345”); public string getName( ) : returns the name of the cookie public string getValue( ) : returns the value of the cookie public void setValue(String _val) : sets the value of the cookie public void setMaxAge(int expiry) : sets the maximum age of the cookie in seconds.
  • 21. 01/30/15 Distributed Computing, M. L. Liu21 Processing Cookies with Java – 2 Java Server Programming – Wrox press public void setPath(java.lang.String uri) : Specifies a path for the cookie to which the client should return the cookie. The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, for example, /catalog, which makes the cookie visible to all directories on the server under /catalog. public java.lang.String getPath() : Returns the path on the server to which the browser returns this cookie. The cookie is visible to all subpaths on the server. public String getDomain( ) : returns the domain of the cookie. • if orea.getDomain.equals(“.foo.com”) • … // do something related to golf public void setDomain(String _domain): sets the cookie’s domain.
  • 22. 01/30/15 Distributed Computing, M. L. Liu22 doGet Method using cookies public void doGet(HttpServletResponse req, HttpServletResponse res) throws ServletException, IOExceiption{ res.setContentType(“text/html”); PrintWriter out = res.getWriter( ); out.println (“<H1>Contents of your shopping cart:</H1>”); Cookie cookies[ ]; cookies = req.getCookies( ); if (cookies != null) { for ( int i = 0; i < cookies.length; i++ ) { if (cookies[i].getName( ).startWith(“Item”)) out.println( cookies[i].getName( ) + “: “ + cookies[i].getValue( )); out.close( ); }
  • 23. 01/30/15 Distributed Computing, M. L. Liu23 Servlet & Cookies Example See Servletcookies folder in code sample: Cart.html: web page to allow selection of items Cart.java: Servlet invoked by Cart.html; it instantiates a cookie object for each items selected. Cart2.html: web page to allow viewing of items currently in cart Cart2.java: Servlet to scan cookies received with the HTTP request and display the contents of each cookie.
  • 24. 01/30/15 Distributed Computing, M. L. Liu24 HTTP Session Objects http://java.sun.com/products/servlet/2.2/javadoc/index.html The javax.servlet.http package provides a public interface HttpSession: Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times.
  • 25. 01/30/15 Distributed Computing, M. L. Liu25 HTTP Session Object - 2 http://java.sun.com/products/servlet/2.2/javadoc/index.html This interface allows servlets to View and manipulate information about a session, such as the session identifier, creation time, and last accessed time Bind objects to sessions, allowing user information to persist across multiple user connections Session object allows session state information to be maintained without depending on the use of cookies (which can be disabled by a browser user.) Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.
  • 26. 01/30/15 Distributed Computing, M. L. Liu26 The Session object A S e s s i o n o b j e c t s e r v e l e t e n g i n e w e b s e r v e r S e r v e r h o s t C l i e n t h o s t r e q u e s t / r e s p o n s e s e r v le t
  • 27. 01/30/15 Distributed Computing, M. L. Liu27 Obtaining an HTTPSession Object • A session object is obtained using the getSession( ) method of the HttpServletRequest object (from doPost or doGet) • public HTTPSession getSession(boolean create): Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null. To make sure the session is properly maintained, you must call this method before the response is committed. public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletRespnse res) throws ServletException, IOException … // get session object HttpSession session = req.getSession(true) if (session != null) { … } …
  • 28. 01/30/15 Distributed Computing, M. L. Liu28 The HTTPSession Object methods public java.lang.String getId( ): returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent. public java.lang.Object getAttribute(java.lang.String name): returns the object bound with the specified name in this session, or null if no object is bound under the name. public java.util.Enumeration getAttributeNames( ): returns an Enumeration of String objects containing the names of all the objects bound to this session. public void removeAttribute(java.lang.String name): removes the object bound with the specified name from this session. If the session does not have an object bound with the specified name, this method does nothing.
  • 29. 01/30/15 Distributed Computing, M. L. Liu29 Session Object example See ServletSession folder in code sample: Cart.html: web page to allow selection of items Cart.java: Servlet invoked by Cart.html; it instantiates a session object which contains descriptions of items selected. Cart2.html: web page to allow viewing of items currently in cart Cart2.java: Servlet to display items in the shopping cart, as recorded by the use a session object in the Cart servlet
  • 30. 01/30/15 Distributed Computing, M. L. Liu30 Summary - 1 A servlet is a Java class. Its code is loaded to a servlet container on the server host. It is initiated by the server in response to a client’s request. Once loaded, a servlet is persistent.
  • 31. 01/30/15 Distributed Computing, M. L. Liu31 Summary - 2 For state information maintenance: hidden form fields cookies the servlet’s instance variables may hold global data a session object can be used to hold session data