SlideShare a Scribd company logo
1 of 39
Download to read offline
JEE - Servlets
Fahad R. Golra
ECE Paris Ecole d'Ingénieurs - FRANCE
Lecture 2 - Servlets
• Request-response model
• Servlet Introduction
• Web Container
• Handling GET and POST
• Servlet Lifecycle
• Servlet API
• Examples
2 JEE - Servlets
Download
• https://dl.dropboxusercontent.com/u/15156388/
Servlets.zip
3
Request-response model
4 JEE - Servlets
HTTP Request
HTTP Response
HTML
<html>
<head>
<body><html>
<head>
<body><html>
<head>
<body>
request
responseclient server
Key elements of request-response
stream
5 JEE - Servlets
HTTP Request
!
!
• HTTP method
• action to be performed
!
• The page to access
• a URL
!
• Form parameters
• variables
HTTP Response
!
!
• Status code
• e.g. error 404
!
• Content type
• text, picture, html, etc
!
• Content
• actual content
Dynamic Content
6 JEE - Servlets
client server
Web container
Servlet
<html>
<head>
<body><html>
<head>
<body><html>
<head>
<body>
Dynamic
content
Static
Content
What Servlets can do
• Create and return an entire HTML Web page containing
dynamic content based on the nature of the client request
• Create a portion of an HTML Web page (an HTML fragment)
that can be embedded in an existing HTML page
• Communicate with other server resources, including
databases and Java-based applications
• Handle connections with multiple clients, accepting input
from and broadcasting results to the multiple clients. A
servlet can be a multi-player game server, for example.
7 JEE - Servlets
What Servlets can do
• Open a new connection from the server to an applet on the
browser and keep the connection open, allowing many data
transfers on the single connection
• Filter data by MIME type for special processing, such as
image conversion and server-side includes (SSI)
• Provide customized processing to any of the server’s
standard routines. For example, a servlet can modify how a
user is authenticated.
8 JEE - Servlets
Why use Servlets ?
• Java
• portable and popular ... it's the heart of the HTTP part of Java EE
!
• power
• You can use all Java APIs,
• Powerful mechanism of annotations,
• Integration across multiple profiles "Java EE" lightweight Web
Profile, big profile "Enterprise" for applications in clusters, etc.
!
• Efficace
• Highly scalable
9 JEE - Servlets
Why use Servlets ?
• Security
• Strong typing,
• Efficient memory management
!
• Strong integration with the server
• Strong exchanges between the server and servlets through
“context” variable: configuration, resource sharing etc.
!
• Scalability & Flexibility
• Theoretically the Servlet model is not for HTTP,
• Powerful mechanisms of "filters" and "chaining" of treatments. More
details later.
10 JEE - Servlets
Web container
11 JEE - Servlets
client server
Web container
HTTP Request
HTTP Response
Request Object
Response Object
Web Container
• Communication support
• Lifecycle management
• Multithreading support
• Security
• JSP support
12 JEE - Servlets
Servlet API
• javax.servlet
• Support generic, protocol-independent servlets	

!
• Servlet (interface)
• GenericServlet (class)	

• service()
• ServletRequest and ServletResponse	

• Provide access to generic server requests and
responses
13 JEE - Servlets
Servlet API
• javax.servlet.http	

• Extended to add HTTP-specific functionality
• HttpServlet (extends GenericServlet )	

• doGet()	

• doPost()	

• HttpServletRequest and HttpServletResponse
• Provide access to HTTP requests and responses
14 JEE - Servlets
User-defined Servlets
• For general servlets, define the service() method.
!
• For HTTP servlets, override one or more of the following
methods as needed:
• doGet()
• doPost()
• doPut()
• doDelete()
!
• Have no main() method
15 JEE - Servlets
doGet() and doPost()
!
protected void doGet(
HttpServletRequest req,
HttpServletResponse resp)
!
protected void doPost(
HttpServletRequest req,
HttpServletResponse resp)
16 JEE - Servlets
doGet() and doPost()
• These methods have two parameters:
!
• The HttpServletRequest object
• Contains the client's request
• Header of the HTTP request
• HTTP parameters (form data or passed with the URL
parameters)
• Other data (cookies, URL, relative path, etc.)
!
• The HttpServletResponse object
• Encapsulates the data back to the client
• HTTP response header (content type, cookies, etc.)
• Response body (as OutputStream)
17 JEE - Servlets
Compare GET vs. POST
18
GET POST
BACK button/Reload Harmless Data will be re-submitted
Bookmarked Can be bookmarked Cannot be bookmarked
Cached Can be cached Not cached
History Parameters remain in
browser history
Parameters are not saved in
browser history
Restrictions on data
length
maximum URL length
is 2048 characters
No restrictions
Restrictions on data
type
Only ASCII characters
allowed
No restrictions. Binary data is also
allowed
Security GET is less secure
because data sent as
part of the URL
!
POST is a little safer because no
browser history and no web server
logs
Visibility Data is visible to
everyone in the URL
Data is not displayed in the URL
Hello World
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

out.println("<html>");

out.println("<head><title>hello world</title></head>");
out.println("<body>");
out.println("<big>hello world</big>");
out.println("</body></html>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}
19 JEE - Servlets
Using JAVA in Servlets- Date Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
!
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = Res response.getWriter();
out.println("<HTML>");

out.println("The time is: " + new java.util.Date());
out.println("</HTML>");
}
}
20 JEE - Servlets
GenericServlet
21 JEE - Servlets
client server
service()
request
response
Handling GET and POST Request
22 JEE - Servlets
GET Request
Response
client server
POST Request
Response
service()
doGet()
doPost()
HTTPServlet Subclass
Web container
Servlet execution process (1/2)
Client
• Makes a request to a servlet
!
Web Server
• Receives the request
• Identifies the request as a servlet request
• Passes the request to the servlet container
!
23 JEE - Servlets
Servlet execution process (2/2)
Servlet Container
• Locates the servlet
• Passes the request to the servlet
!
Servlet
• Executes in the current thread
• The servlet can store/retrieve objects from the container
• Output is sent back to the requesting browser via the
web server
• Servlet continues to be available in the servlet container
!
24 JEE - Servlets
Servlet Container
• Provides web server with servlet support
• Execute and manage servlets
• e.g., Tomcat
!
• Must conform to the following lifecycle contract
• Create and initialize the servlet
• Handle zero or more service calls from clients
• Destroy the servlet and then garbage collect it
!
• Servlet Container types
• Standalone container
• Add-on container
• Embeddable container
25 JEE - Servlets
Servlet Lifecycle
26 JEE - Servlets
Loading Servlet
• The init() method executes only one time during the lifetime
of the servlet.
• It is not repeated regardless of how many clients access
the servlet
• It can be overridden to manage servlet-wide resources.
• for example is initializing a database connection
!
• May be called ...	

• When the server starts	

• When the servlet is first requested, just before the service() method
is invoked	

• At the request of the server administrator
27 JEE - Servlets
Unloading Servlet
• The destroy() method executes only one time
• when the server stops and unloads the servlet
!
• destroy()
• Resources acquired should be freed up
• A chance to write out its unsaved cached info
• Last step before being garbage collected
!
• It can be overridden, typically to manage servlet-wide
resources.
• for example, closing a database connection
28 JEE - Servlets
service()
• The service() method is invoked for each client
request.
• In HttpServlet, the default service function invokes the
do function corresponding to the method of the HTTP
request.
• If the form information is provided by GET, the doGet()
method is invoked
• If the form information is provided by POST, the doPost()
method is invoked
• When a client invokes a servlet directly by the servlet’s URL,
the client uses GET
29 JEE - Servlets
Servlet Instance Persistence
• Servlets persist between requests as object instances
• When servlet is loaded, the server creates a single instance 	

• The single instance handles every request made of the
servlet 	

• Improves performance in three ways
• Keeps memory footprint small
• Eliminates the object creation overhead	

• Enables persistence
• May have already loaded required resources
30 JEE - Servlets
Servlet Thread Model
31 JEE - Servlets
Request for
Servlet 1
Request for
Servlet 2
Request for
Servlet 1
Servlet 1
Thread
Servlet 2
Thread
Thread
JVM
Main Process
Servlet-based Web Server
Servlets API details
• Main functions of a Servlet:
!
• Treat HTTP parameters received in the request
(GET or POST)
• HttpServletRequest.getParameter (String)
!
• Retrieve a configuration parameter of the web
application (in the web.xml descriptor)
• ServletConfig.getInitParameter ()
!
• Recover a part of the HTTP header
• HttpServletRequest.getHeader (String)
32 JEE - Servlets
Servlets API details
• Specify the response type in the header
• HttpServletResponse.setHeader (<name>, <value>) /
HttpServletResponse.setContentType (String)
!
• Retrieve a Writer to write the response
• HttpServletResponse.getWriter ()
!
• or ... if the response is binary
• HttpServletResponse.getOutputStream ()
!
• Redirect the request to another URL
• HttpServletResponse.sendRedirect ()
33 JEE - Servlets
Getting Request information
• The Request object has specific methods to retrieve
information provided by the client:
• getParameterNames()
• returns a string array containing the parameters
• getParameter()
• when provided a parameter name, returns its
corresponding value
• getParameterValues()
34 JEE - Servlets
Returning Response information
• The Response object creates a response to return to
the requesting client.
• Response header
• Response body
!
• The Response object also has the getWriter() method
to return a PrintWriter object.
• Use the print() and println() methods
35 JEE - Servlets
Example: Parameters
<html>
<body>


<form method="GET" action="HelloServlet">
Enter your name :

<input type="text" name="name">
<input type="submit" value="OK">
</form>
!
</body>
</html>
36 JEE - Servlets
Example: Parameters
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
String nom = request.getParameter("name");
out.println("<html><head>");
out.println("t<title>Hello Servlet</title>");
out.println("</head><body>");
out.println("t<h1>Hello, " + nom + "</h1>");
out.println("</body></html>");
}
}
37 JEE - Servlets
Sending a zip through Servlet
Example from http://www.kodejava.org/examples/590.html
!
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {	

	

 try {

String path = getServletContext().getRealPath("data");
File directory = new File(path);

String[] files = directory.list();

if (files != null && files.length > 0) {	

	

 byte[] zip = zipFiles(directory, files);	

	

 ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename="DATA.ZIP"");
sos.write(zip); sos.flush();
}
} catch (Exception e) {	

	

 	

 e.printStackTrace();
}	

}
38
39 JEE - Servlets

More Related Content

What's hot

Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final) Hitesh-Java
 
D2W Branding Using jQuery ThemeRoller
D2W Branding Using jQuery ThemeRollerD2W Branding Using jQuery ThemeRoller
D2W Branding Using jQuery ThemeRollerWO Community
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 
Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Ryan Cuprak
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
Java web application development
Java web application developmentJava web application development
Java web application developmentRitikRathaur
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2PawanMM
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicIMC Institute
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicIMC Institute
 

What's hot (19)

Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
D2W Branding Using jQuery ThemeRoller
D2W Branding Using jQuery ThemeRollerD2W Branding Using jQuery ThemeRoller
D2W Branding Using jQuery ThemeRoller
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 

Viewers also liked

Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Fahad Golra
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)Fahad Golra
 
Tutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital PhotographyTutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital PhotographyFahad Golra
 
TNAPS 3 Installation
TNAPS 3 InstallationTNAPS 3 Installation
TNAPS 3 Installationtncor
 
Ejb in java. part 1.
Ejb in java. part 1.Ejb in java. part 1.
Ejb in java. part 1.Asya Dudnik
 
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!Омские ИТ-субботники
 
Apache Lucene + Hibernate = Hibernate Search
Apache Lucene + Hibernate = Hibernate SearchApache Lucene + Hibernate = Hibernate Search
Apache Lucene + Hibernate = Hibernate SearchVitebsk Miniq
 
JMS Introduction
JMS IntroductionJMS Introduction
JMS IntroductionAlex Su
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedBG Java EE Course
 
The Modern Java Web Developer Bootcamp - Devoxx 2013
The Modern Java Web Developer Bootcamp - Devoxx 2013The Modern Java Web Developer Bootcamp - Devoxx 2013
The Modern Java Web Developer Bootcamp - Devoxx 2013Matt Raible
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSocketsGunnar Hillert
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJBPeter R. Egli
 
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging ServicePeter R. Egli
 
Comparing JVM Web Frameworks - February 2014
Comparing JVM Web Frameworks - February 2014Comparing JVM Web Frameworks - February 2014
Comparing JVM Web Frameworks - February 2014Matt Raible
 
A day in the life
A day in the lifeA day in the life
A day in the lifegreteeg16
 

Viewers also liked (20)

Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
Tutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital PhotographyTutorial 4 - Basics of Digital Photography
Tutorial 4 - Basics of Digital Photography
 
TNAPS 3 Installation
TNAPS 3 InstallationTNAPS 3 Installation
TNAPS 3 Installation
 
Ejb in java. part 1.
Ejb in java. part 1.Ejb in java. part 1.
Ejb in java. part 1.
 
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
 
Apache Lucene + Hibernate = Hibernate Search
Apache Lucene + Hibernate = Hibernate SearchApache Lucene + Hibernate = Hibernate Search
Apache Lucene + Hibernate = Hibernate Search
 
JMS Introduction
JMS IntroductionJMS Introduction
JMS Introduction
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
The Modern Java Web Developer Bootcamp - Devoxx 2013
The Modern Java Web Developer Bootcamp - Devoxx 2013The Modern Java Web Developer Bootcamp - Devoxx 2013
The Modern Java Web Developer Bootcamp - Devoxx 2013
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
EJB .
EJB .EJB .
EJB .
 
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging Service
 
Domain object model
Domain object modelDomain object model
Domain object model
 
Comparing JVM Web Frameworks - February 2014
Comparing JVM Web Frameworks - February 2014Comparing JVM Web Frameworks - February 2014
Comparing JVM Web Frameworks - February 2014
 
A day in the life
A day in the lifeA day in the life
A day in the life
 
Avnet Analyst Day 2010 Presentation 6 Summary
Avnet Analyst Day 2010 Presentation 6 SummaryAvnet Analyst Day 2010 Presentation 6 Summary
Avnet Analyst Day 2010 Presentation 6 Summary
 
Munduari bira
Munduari biraMunduari bira
Munduari bira
 

Similar to Lecture 2: Servlets

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Anas Sa
 
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 KuteTushar B Kute
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2PawanMM
 

Similar to Lecture 2: Servlets (20)

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Servlets
ServletsServlets
Servlets
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Servlets
ServletsServlets
Servlets
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation
 
19servlets
19servlets19servlets
19servlets
 
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
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
CS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptxCS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptx
 

More from Fahad Golra

Seance 4- Programmation en langage C
Seance 4- Programmation en langage CSeance 4- Programmation en langage C
Seance 4- Programmation en langage CFahad Golra
 
Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Fahad Golra
 
Seance 2 - Programmation en langage C
Seance 2 - Programmation en langage CSeance 2 - Programmation en langage C
Seance 2 - Programmation en langage CFahad Golra
 
Seance 1 - Programmation en langage C
Seance 1 - Programmation en langage CSeance 1 - Programmation en langage C
Seance 1 - Programmation en langage CFahad Golra
 
Tutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital PhotographyTutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital PhotographyFahad Golra
 
Tutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital PhotographyTutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital PhotographyFahad Golra
 
Tutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital PhotographyTutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital PhotographyFahad Golra
 
Deviation Detection in Process Enactment
Deviation Detection in Process EnactmentDeviation Detection in Process Enactment
Deviation Detection in Process EnactmentFahad Golra
 
Meta l metacase tools & possibilities
Meta l metacase tools & possibilitiesMeta l metacase tools & possibilities
Meta l metacase tools & possibilitiesFahad Golra
 

More from Fahad Golra (9)

Seance 4- Programmation en langage C
Seance 4- Programmation en langage CSeance 4- Programmation en langage C
Seance 4- Programmation en langage C
 
Seance 3- Programmation en langage C
Seance 3- Programmation en langage C Seance 3- Programmation en langage C
Seance 3- Programmation en langage C
 
Seance 2 - Programmation en langage C
Seance 2 - Programmation en langage CSeance 2 - Programmation en langage C
Seance 2 - Programmation en langage C
 
Seance 1 - Programmation en langage C
Seance 1 - Programmation en langage CSeance 1 - Programmation en langage C
Seance 1 - Programmation en langage C
 
Tutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital PhotographyTutorial 3 - Basics of Digital Photography
Tutorial 3 - Basics of Digital Photography
 
Tutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital PhotographyTutorial 2 - Basics of Digital Photography
Tutorial 2 - Basics of Digital Photography
 
Tutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital PhotographyTutorial 1 - Basics of Digital Photography
Tutorial 1 - Basics of Digital Photography
 
Deviation Detection in Process Enactment
Deviation Detection in Process EnactmentDeviation Detection in Process Enactment
Deviation Detection in Process Enactment
 
Meta l metacase tools & possibilities
Meta l metacase tools & possibilitiesMeta l metacase tools & possibilities
Meta l metacase tools & possibilities
 

Recently uploaded

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

Lecture 2: Servlets

  • 1. JEE - Servlets Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE
  • 2. Lecture 2 - Servlets • Request-response model • Servlet Introduction • Web Container • Handling GET and POST • Servlet Lifecycle • Servlet API • Examples 2 JEE - Servlets
  • 4. Request-response model 4 JEE - Servlets HTTP Request HTTP Response HTML <html> <head> <body><html> <head> <body><html> <head> <body> request responseclient server
  • 5. Key elements of request-response stream 5 JEE - Servlets HTTP Request ! ! • HTTP method • action to be performed ! • The page to access • a URL ! • Form parameters • variables HTTP Response ! ! • Status code • e.g. error 404 ! • Content type • text, picture, html, etc ! • Content • actual content
  • 6. Dynamic Content 6 JEE - Servlets client server Web container Servlet <html> <head> <body><html> <head> <body><html> <head> <body> Dynamic content Static Content
  • 7. What Servlets can do • Create and return an entire HTML Web page containing dynamic content based on the nature of the client request • Create a portion of an HTML Web page (an HTML fragment) that can be embedded in an existing HTML page • Communicate with other server resources, including databases and Java-based applications • Handle connections with multiple clients, accepting input from and broadcasting results to the multiple clients. A servlet can be a multi-player game server, for example. 7 JEE - Servlets
  • 8. What Servlets can do • Open a new connection from the server to an applet on the browser and keep the connection open, allowing many data transfers on the single connection • Filter data by MIME type for special processing, such as image conversion and server-side includes (SSI) • Provide customized processing to any of the server’s standard routines. For example, a servlet can modify how a user is authenticated. 8 JEE - Servlets
  • 9. Why use Servlets ? • Java • portable and popular ... it's the heart of the HTTP part of Java EE ! • power • You can use all Java APIs, • Powerful mechanism of annotations, • Integration across multiple profiles "Java EE" lightweight Web Profile, big profile "Enterprise" for applications in clusters, etc. ! • Efficace • Highly scalable 9 JEE - Servlets
  • 10. Why use Servlets ? • Security • Strong typing, • Efficient memory management ! • Strong integration with the server • Strong exchanges between the server and servlets through “context” variable: configuration, resource sharing etc. ! • Scalability & Flexibility • Theoretically the Servlet model is not for HTTP, • Powerful mechanisms of "filters" and "chaining" of treatments. More details later. 10 JEE - Servlets
  • 11. Web container 11 JEE - Servlets client server Web container HTTP Request HTTP Response Request Object Response Object
  • 12. Web Container • Communication support • Lifecycle management • Multithreading support • Security • JSP support 12 JEE - Servlets
  • 13. Servlet API • javax.servlet • Support generic, protocol-independent servlets ! • Servlet (interface) • GenericServlet (class) • service() • ServletRequest and ServletResponse • Provide access to generic server requests and responses 13 JEE - Servlets
  • 14. Servlet API • javax.servlet.http • Extended to add HTTP-specific functionality • HttpServlet (extends GenericServlet ) • doGet() • doPost() • HttpServletRequest and HttpServletResponse • Provide access to HTTP requests and responses 14 JEE - Servlets
  • 15. User-defined Servlets • For general servlets, define the service() method. ! • For HTTP servlets, override one or more of the following methods as needed: • doGet() • doPost() • doPut() • doDelete() ! • Have no main() method 15 JEE - Servlets
  • 16. doGet() and doPost() ! protected void doGet( HttpServletRequest req, HttpServletResponse resp) ! protected void doPost( HttpServletRequest req, HttpServletResponse resp) 16 JEE - Servlets
  • 17. doGet() and doPost() • These methods have two parameters: ! • The HttpServletRequest object • Contains the client's request • Header of the HTTP request • HTTP parameters (form data or passed with the URL parameters) • Other data (cookies, URL, relative path, etc.) ! • The HttpServletResponse object • Encapsulates the data back to the client • HTTP response header (content type, cookies, etc.) • Response body (as OutputStream) 17 JEE - Servlets
  • 18. Compare GET vs. POST 18 GET POST BACK button/Reload Harmless Data will be re-submitted Bookmarked Can be bookmarked Cannot be bookmarked Cached Can be cached Not cached History Parameters remain in browser history Parameters are not saved in browser history Restrictions on data length maximum URL length is 2048 characters No restrictions Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also allowed Security GET is less secure because data sent as part of the URL ! POST is a little safer because no browser history and no web server logs Visibility Data is visible to everyone in the URL Data is not displayed in the URL
  • 19. Hello World import java.io.*;
 import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter();
 out.println("<html>");
 out.println("<head><title>hello world</title></head>"); out.println("<body>"); out.println("<big>hello world</big>"); out.println("</body></html>"); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } } 19 JEE - Servlets
  • 20. Using JAVA in Servlets- Date Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; ! public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = Res response.getWriter(); out.println("<HTML>");
 out.println("The time is: " + new java.util.Date()); out.println("</HTML>"); } } 20 JEE - Servlets
  • 21. GenericServlet 21 JEE - Servlets client server service() request response
  • 22. Handling GET and POST Request 22 JEE - Servlets GET Request Response client server POST Request Response service() doGet() doPost() HTTPServlet Subclass Web container
  • 23. Servlet execution process (1/2) Client • Makes a request to a servlet ! Web Server • Receives the request • Identifies the request as a servlet request • Passes the request to the servlet container ! 23 JEE - Servlets
  • 24. Servlet execution process (2/2) Servlet Container • Locates the servlet • Passes the request to the servlet ! Servlet • Executes in the current thread • The servlet can store/retrieve objects from the container • Output is sent back to the requesting browser via the web server • Servlet continues to be available in the servlet container ! 24 JEE - Servlets
  • 25. Servlet Container • Provides web server with servlet support • Execute and manage servlets • e.g., Tomcat ! • Must conform to the following lifecycle contract • Create and initialize the servlet • Handle zero or more service calls from clients • Destroy the servlet and then garbage collect it ! • Servlet Container types • Standalone container • Add-on container • Embeddable container 25 JEE - Servlets
  • 27. Loading Servlet • The init() method executes only one time during the lifetime of the servlet. • It is not repeated regardless of how many clients access the servlet • It can be overridden to manage servlet-wide resources. • for example is initializing a database connection ! • May be called ... • When the server starts • When the servlet is first requested, just before the service() method is invoked • At the request of the server administrator 27 JEE - Servlets
  • 28. Unloading Servlet • The destroy() method executes only one time • when the server stops and unloads the servlet ! • destroy() • Resources acquired should be freed up • A chance to write out its unsaved cached info • Last step before being garbage collected ! • It can be overridden, typically to manage servlet-wide resources. • for example, closing a database connection 28 JEE - Servlets
  • 29. service() • The service() method is invoked for each client request. • In HttpServlet, the default service function invokes the do function corresponding to the method of the HTTP request. • If the form information is provided by GET, the doGet() method is invoked • If the form information is provided by POST, the doPost() method is invoked • When a client invokes a servlet directly by the servlet’s URL, the client uses GET 29 JEE - Servlets
  • 30. Servlet Instance Persistence • Servlets persist between requests as object instances • When servlet is loaded, the server creates a single instance • The single instance handles every request made of the servlet • Improves performance in three ways • Keeps memory footprint small • Eliminates the object creation overhead • Enables persistence • May have already loaded required resources 30 JEE - Servlets
  • 31. Servlet Thread Model 31 JEE - Servlets Request for Servlet 1 Request for Servlet 2 Request for Servlet 1 Servlet 1 Thread Servlet 2 Thread Thread JVM Main Process Servlet-based Web Server
  • 32. Servlets API details • Main functions of a Servlet: ! • Treat HTTP parameters received in the request (GET or POST) • HttpServletRequest.getParameter (String) ! • Retrieve a configuration parameter of the web application (in the web.xml descriptor) • ServletConfig.getInitParameter () ! • Recover a part of the HTTP header • HttpServletRequest.getHeader (String) 32 JEE - Servlets
  • 33. Servlets API details • Specify the response type in the header • HttpServletResponse.setHeader (<name>, <value>) / HttpServletResponse.setContentType (String) ! • Retrieve a Writer to write the response • HttpServletResponse.getWriter () ! • or ... if the response is binary • HttpServletResponse.getOutputStream () ! • Redirect the request to another URL • HttpServletResponse.sendRedirect () 33 JEE - Servlets
  • 34. Getting Request information • The Request object has specific methods to retrieve information provided by the client: • getParameterNames() • returns a string array containing the parameters • getParameter() • when provided a parameter name, returns its corresponding value • getParameterValues() 34 JEE - Servlets
  • 35. Returning Response information • The Response object creates a response to return to the requesting client. • Response header • Response body ! • The Response object also has the getWriter() method to return a PrintWriter object. • Use the print() and println() methods 35 JEE - Servlets
  • 36. Example: Parameters <html> <body> 
 <form method="GET" action="HelloServlet"> Enter your name :
 <input type="text" name="name"> <input type="submit" value="OK"> </form> ! </body> </html> 36 JEE - Servlets
  • 37. Example: Parameters import java.io.*;
 import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); String nom = request.getParameter("name"); out.println("<html><head>"); out.println("t<title>Hello Servlet</title>"); out.println("</head><body>"); out.println("t<h1>Hello, " + nom + "</h1>"); out.println("</body></html>"); } } 37 JEE - Servlets
  • 38. Sending a zip through Servlet Example from http://www.kodejava.org/examples/590.html ! protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {
 String path = getServletContext().getRealPath("data"); File directory = new File(path);
 String[] files = directory.list();
 if (files != null && files.length > 0) { byte[] zip = zipFiles(directory, files); ServletOutputStream sos = response.getOutputStream(); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;filename="DATA.ZIP""); sos.write(zip); sos.flush(); } } catch (Exception e) { e.printStackTrace(); } } 38
  • 39. 39 JEE - Servlets