Vous êtes sur la page 1sur 104

Servlet Basics

What is A Servlet?
 Servlets are pieces of Java source code that add
functionality to a web server in a manner similar to the
way applets add functionality to a browser.

 Servlets are server-side software components, written


in Java and run inside a server .

 Servlets are loaded and executed within the Java


Virtual Machine (JVM) of the server, in much the same
way that applets are loaded and executed within the
JRE of the Web client.

 Works on request /response model


Servlet
Multitiered J2EE applications
J2EE Components
 The J2EE specification defines the following J2EE
components:

 Application clients and applets are components that run on


the client.

 Java Servlet and JavaServer Pages (JSP ) technology


components are web components that run on the server.

 Enterprise JavaBeans (EJB ) components (enterprise beans)


are business components that run on the server.
Where are Servlet and JSP?
J2EE Container
First Servlet Code
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Hello World!</title>");
}
...
}
CGI versus Servlet
CGI versus Servlet
Java Servlet-based Web Server

Main Process
Request for JVM
Servlet 1 Thread
Servlet1
Servlet1
Request for Thread
Servlet 2
Thread Servlet2
Servlet2
Request for
Servlet 1
CGI versus Servlet
Advantages of Servlet
 No CGI limitations
 Abundant third-party tools and Web servers
supporting Servlet
 Access to entire family of Java APIs
 Reliable, better performance and scalability
 Platform and server independent
 Secure
HTTP Basics
 HTTP is a simple, stateless protocol .
 A client makes a request and the web server
responds.

For example:
GET /intro.html HTTP/1.0

 the client sends an HTTP command, a method, that


tells the server the type of action .
 also specifies the address of a document (a URL) and
the version of the HTTP protocol it is using.
Http Basics cont..
 After the client sends the request, the server
processes it and sends back a response.

For example :
HTTP/1.0 200 OK

 the response specifies the version of the HTTP


protocol the server is using, a status code, and a
description of the status code.
HTTP GET and POST
 The most common client requests
– HTTP GET & HTTP POST

 GET requests:
– User entered information is appended to the URL in
a query string
– Can only send limited amount of data

 POST requests:
– User entered information is sent as data (not
appended to URL)
– Can send any amount of data
Demo
GET Request
POST Request
Servlet Request and Response Model
What are Servlets?
 Servlets are programs that run on a Web server .

 Act as a middle layer between a request coming from


a Web browser or other HTTP client and databases or
applications on the HTTP server.
What Servlet does?

Servlets job is to:


 Read any data sent by the user.
 Look up any other information about the request that is
embedded in the HTTP request.
 Generate the results.
 Format the results inside a document.
 Set the appropriate HTTP response parameters.
 Send the document back to the client.
Servlet Request and Response
model
Requests and Responses
 What is a request?
– Information that is sent from client to a server
* Who made the request
* What user-entered data is sent
* Which HTTP headers are sent
 What is a response?
– Information that is sent to client from a server
* Text(html, plain) or binary(image) data
* HTTP headers, cookies, etc
Servlet API
Servlet API
 Servlets use classes and interfaces from two
packages :

 Generic (protocol-independent) servlet classes:


javax.servlet.

 HTTP specific servlet classes:


javax.servlet.http.
Servlet Classes and Interfaces
Servlet
 Servlet does not have a main() method.

 Each time the server dispatches a request to a servlet


it invokes the servlet’s service() method.
Servlet API
Servlet Interface (javax.servlet.Servlet)
This interface has the servlet life cycle methods .

GenericServlet Class(javax.servlet.GenericServlet)
A protocol independent servlet should subclass
this servlet & should override the service()
method.
HttpServlet Class(javax.servlet.http.HttpServlet)
 An abstract class that implements the service()
method to reflect the HTTPness of the servlet .
 The subclass should not override the service
method .
Calling service() method
Calling doGet() / doPost()
Writing 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>");
}
}
Servlet Life Cycle
Servlet Life Cycle
First Client Request
When the first client request comes :

 Container creates the servlet instance .

 Invokes its init() method .

 Later, each user request results in a thread that calls the


service() method of the previously created instance.

 The service method then calls doGet(), doPost(), or another


doXxx method depending on the type of HTTP request it
received.

 Finally, when the server decides to unload a servlet, it first calls


the servlet’s destroy() method.
Servlet Life Cycle
Servlet Life Cycle methods
init()
 Executed once when the servlet is first loaded.
 Not called for each request.
 Perform any one time set-up code in this method.

service()
 Called in a new thread by server for each request.
 Dispatches to doGet, doPost, etc.

doGet(), doPost(), doXxx()


 Handles GET, POST, etc. requests.
 Override these to provide desired behavior.

destroy()
 Called when server deletes servlet instance.
 Perform any clean-up, and save data to be read by the next init().
service() method
doGet() / doPost()
First Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println(“</B>Wel-Come!</B>");
}
}
Container controls the Servlet
 After receiving request from the client container creates two
objects:
 HttpServletRequest

 HttpServletResponse

 The container finds the correct servlet based on the


URL in the request .
 creates a thread for that servlet.
Calling service method()

 Calls the servlet’s service() method passing the


request and response objects as arguments .

 Based on the Http method, service() method calls the


doGet()/doPost() method passing the request and
response objects as arguments .
Sending response to client
 Servlet uses the response object to write out to client
through the container .

 The client gets the response .


Servlet Request
Servlet Request
 Contains data passed from client to servlet .

 All servlet requests implement ServletRequest interface which


defines methods for accessing Client sent parameters , Object-
valued attributes etc..
Getting Client Sent
Parameters
 A request can come with any number of parameters

 Parameters are sent from HTML forms:

– GET: as a query string, appended to a URL


– POST: as encoded POST data, not appeared in the URL

 getParameter( “paramName” )

– Returns the value of paramName


– Returns null if no such parameter is present
– Works identically for GET and POST requests
HTTPServletRequest
 Contains data passed from HTTP client to HTTP servlet
 Created by servlet container and passed to servlet as a
parameter of doGet() or doPost() methods
 HttpServletRequest is an extension of ServletRequest
and provides additional methods for accessing

– HTTP request URL


Context, servlet, query information
– Misc. HTTP Request header information
– Authentication type & User security information
– Cookies
– Session
URI - Uniform Resource Identifier

 Identifies the resource on host machine and


access method for that resource.
 E.g. http://www.yahoo.com/index.html

 3 parts
 Scheme or protocol.
 DNS name of the host.

 File name on the host.


HTTP Request URL

 Contains the following parts


– http://[host]:[port]/[request path]?[query
string]
HTTP Request URL:
[request path]
 http://[host]:[port]/[request path]?[query
string]
 [request path] is made of
– Context: /<context of web app>
– Servlet name: /<component alias>

Examples
– http://localhost:7001/hello1/greeting
– http://localhost:7001/hello1/greeting.jsp
HTTP Request URL:
[query string]
 http://[host]:[port]/[request path]?[query string]
 [query string] are composed of a set of parameters and
values that are user entered
 Two ways query strings are generated
– A query string can explicitly appear in a web page
 <a href= “NewPage?Add=101”>Click Here</a>
 String bookId = request.getParameter( “Add” );
– A query string is appended to a URL when a form with
a GET HTTP method is submitted
 http://localhost/hello1/greeting?username=Monica+Clinton
 String userName=request.getParameter(“username”)
Context, Path, Query,
ParameterMethods

 String getContextPath()

 String getQueryString()

 String getParameter(String paramName)

 String[] getParameterValues(String paramName)

 Enumeration getParameterNames()
HTTP Request
 Client sends a request
 Request method, URI, and protocol version.

 Request headers

 request modifiers, client information.

 A blank line.

 Optional body contents.


HTTP Request Headers
 HTTP requests include headers which provide extra information
about the request
 Example of HTTP 1.1 Request:

host : localhost:8080

user-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;


SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; InfoPath.1;
.NET CLR 3.0.04506.648)

referrer :
http://localhost:8080/ServletProject/HandleRequestDataForm.html
HTTP Header Methods
 String getHeader(java.lang.String name)
– value of the specified request header as String
 java.util.Enumeration getHeaders(java.lang.String name)
– values of the specified request header
 java.util.Enumeration getHeaderNames()
– names of request headers
 int getIntHeader(java.lang.String name)
– value of the specified request header as an int
Servlet Response
What is Servlet Response?
 Contains data passed from servlet to client
 All servlet responses implement ServletResponse
interface
– Retrieve an output stream
– Indicate content type
– Indicate whether to buffer output
– Set localization information
 HttpServletResponse extends ServletResponse
– HTTP response status code
– Cookies
Responses
Http Response
Server responds back with
 Status line including message protocol version and a
status code.
 Several message headers
server information, entity meta-information.
 Optional body contents.
Header in HTTP Response
Why HTTP Response Headers?
 Give forwarding location
 Specify cookies
 Supply the page modification date
 Instruct the browser to reload the page after a
designated interval
 Give the file size so that persistent HTTP connections
can be used
 Designate the type of document being generated .
Methods for Setting Arbitrary
Response Headers
 public void setHeader( String headerName, String
headerValue)
 public void setDateHeader( String name, long millisecs)
 public void setIntHeader( String name, int headerValue)
 addHeader, addDateHeader, addIntHeader
 setContentType
 setContentLength
 addCookie
 sendRedirect
Body in HttpResponse
Writing a Response Body
 A servlet almost always returns a response body
 Response body could either be a PrintWriter or a
ServletOutputStream
 PrintWriter
– Using response.getWriter()
– For character-based output
 ServletOutputStream
– Using response.getOutputStream()
– For binary (image) data
Web Application Deployment
Web Application
 A Web Application is ,
a collection of servlets,JSP,HTML documents, images
and other web resources that are setup in such a way
as to be portably deployed across any servlet enabled
web server.

 Each Web Application consists of

• Configuration file web.xml


• Static files and JSP
• Class files.
Tomcat Structure
Apache Tomcat Server

 Tomcat can handle Web pages, Servlets, and JSPs


 Includes a servlet container used for testing and
deploying servlets .
 Tomcat is open source (free)
Configuring Tomcat
 By editing server.xml (conf/server.xml), we can
change the port where Tomcat will listen for HTTP
requests.
 By default the port is 8080.

<!-- Define a non-SSL Coyote HTTP/1.1


Connector on the port specified during
installation -->
<Connector port= "8080"
maxThreads="150" minSpareThreads="25"
maxSpareThreads="75“
enableLookups="false" redirectPort="8443"
acceptCount="100“ debug="0"
connectionTimeout="20000"
disableUploadTimeout="true" />
Web Application : Static parts
Web Application : WEB-INF
WEB-INF Directory

– web.xml :
 Web application deployment descriptor that contains meta-data for
the web application.

 used by the container while loading the web application.

 File is always located in the WEB-INF directory of the web


application.
web.xml and WEB-INF

– classes :
A directory that contains server-side classes: servlets,
utility classes, and JavaBeans components

– lib :
A directory that contains JAR archives of libraries (tag libraries
and any utility libraries called by server-side classes)

 The WEB-INF directory is kept hidden from the users of the Web
application.
WEB-INF : Forbidden
Steps for creating a web
application
 Create a directory called MyWebapp in the /webapps folder of your
Tomcat
 Create a sub-directory WEB-INF inside MyWebApp.

 Inside WEB-INF create a web.xml file as shown below :

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.4//EN"
"http://java.sun.com/dtd/web-app_2_4.dtd">
<web-app>
</web-app>

 Create a classes sub-directory to place the server


side classes .
JAR and WAR
 Java Archive file is a convenient method for
consolidating a set of Java classes into one
compressed portable file.

 Any JAR file in the WEB-INF/lib directory of a web


application is made for use by the code in the same
web app.
WAR
 Web Application Resource files are similar to JAR files but are
used to consolidate the entire web application into one
compressed portable file.
ServletConfig Interface
init() method
init() method is used to perform servlet initialization .

There are two versions of init:

 one that takes no arguments


 one that takes a ServletConfig object as an argument

The first version of init looks like this:

public void init() throws ServletException {


// Initialization code...
}
init(ServletConfig config)
 The second version of init is used when the servlet
needs to read server-specific settings before it can
complete the initialization.

The second version of init looks like this:

public void init(ServletConfig config)


throws ServletException {
super.init(config); //this is necessary
// Initialization code...
}
Which init to use ?
 If the init(ServletConfig config) is used then it is
important to have super.init(config) as its first line.
 You can use this.servletconfig = config to store the
ServletConfig object.

 The no-arg init() method is a convenience method


provided by the API.

 You can use getServletConfig() method to get the


ServletConfig object.
ServletConfig methods

 ServletConfig methods
 String getInitParameter(String name)
 Enumeration getInitParameterNames()
 ServletContext getServletContext()
 String getServletName()
Assigning Servlet Initialization
Parameters
<servlet>
<servlet-name>InitTest</servlet-name>
<servlet-class>
moreservlets.InitServlet
</servlet-class>
<init-param>
<param-name>firstName</param-name>
<param-value>abc</param-value>
</init-param>
<init-param>
<param-name>emailAddress</param-name>
<param-value>abc@microsoft.com</param-value>
</init-param>
</servlet>
Reading Servlet Initialization
Parameters
public class InitServlet extends HttpServlet {

private String firstName, emailAddress;

public void init() {


ServletConfig config = getServletConfig();
firstName =config.getInitParameter("firstName");
emailAddress =config.getInitParameter("emailAddress");
}

public void doGet(…) … { … }


}
ServletContext class
ServletContext
 Context init parameters are available to entire web application.

 Any servlet in the application has access to the context init


parameter.

 There is one ServletContext object per web application .


Setting parameters

web.xml element: context-param

<context-param>
<param-name>support-email</param-name>
<param-value>pqr@mycompany.com</param-value>
</context-param>

Invoking context parameter from a servlet :

ServletContext context=getServletContext();
out.println(context.getInitParameter(“support-email”));
Including, Forwarding, Redirecting
to other Web resources
Including, Forwarding, Redirecting
to other Web resources

 You do not want to deal with the response rather want another
web component to handle the request ?

There are two options to follow :

 Redirect the request to a completely different URL.


 Dispatch the request to some other component in the web
application .
Redirecting the Request
 A client types a URL into the browser and a servlet is located :

• Suppose the servlet decides to send the request to a completely


different URL .
• It calls sendRedirect(“NewURL”) on the response .
• the client gets the response and makes a new request for the
“NewURL” .
• The specific web component is called ,the request gets fulfilled
and the response is send back to the client.

Redirect makes the browser do the work.


Redirecting a Request
 Programming model for directing a request
public void sendRedirect(String url)

if(doTheWork){
//handle the request
} else {
response.sendRedirect(http://www.oreilly.com);
}
 You can use Relative URLs
 You can’t do a sendRedirect() after writing to the
response
Relative URLs
 Two ways
Original : http://www.wickedlysmart.com/myApp/cool/bar
.do
If in Servlet (without forward slash(“/ ”)):
sendRedirect(“foo/stuff.html”);

Container builds the full URL as :


http://www.wickedlysmart.com/myApp/cool/foo/stuff.html
OR
If in Servlet (with forward slash(“/”)):
sendRedirect(“/foo/stuff.html”);
Container builds the full URL as :
http://www.wickedlysmart.com/myApp/foo/stuff.html
Using RequestDispatcher
 A client types a URL into the browser and a servlet is located :

• Suppose the servlet decides to send the request to a completely


different URL .

• It calls :
RequestDispatcher view =
request.getRequestDispatcher(“abc.jsp”);
view.forward(request,response);

• abc.jsp takes over the response .

• The client gets the response in usual way , the user does not know
that the JSP generated the response .
RequestDispatcher
 Request dispatch does the work on the server side i.e.
transparent to the browser .
 The method getRequestDispatcher(String path) in class
ServletRequest helps dispatching the request

public RequestDispatcher getRequestDispatcher(String path)


RequestDispatcher Methods
 void forward(ServletRequest request,
ServletResponse response)

 void include(ServletRequest request,


ServletResponse response)
Forward with RequestDispatcher
Example
public void doPost(HttpServletRequest req, HttpServletResponse
res)
{
String userid = req.getParameter("userid");
String password = req.getParameter("password");
if( userid != null && password != null &&
password.equals(users.get(userid)) )
{
req.setAttribute("userid", userid);
ServletContext ct = getServletContext();
RequestDispatcher rd =
ct.getRequestDispatcher("/servlet/AccountServlet");
rd.forward(req, res);
return;
}
else
RequestDispatcher Example
Cont..

{
RequestDispatcher rd =
req.getRequestDispatcher("../login.html");
rd.forward(req, res);
return;
}
}
Including another Web
Resource
When to Include another Web
resource?

 When it is useful to add static or dynamic


contents already created by another web
resource
– Adding a banner content or copyright information in
the response returned from a Web component
Example: Including a Servlet

RequestDispatcher dispatcher
getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null)
dispatcher.include(request, response);
}
Scope Objects
Scope Objects
 Enables sharing information among collaborating web
components via attributes maintained in Scope objects
– Attributes are name/object pairs
 Attributes maintained in the Scope objects are
accessed with
– getAttribute() & setAttribute()
 3 Scope objects are defined
– Web context, session, request
Scope Objects : Class
 Web context (ServletConext)
– javax.servlet.ServletContext
 Session
– javax.servlet.http.HttpSession
 Request
– subtype of javax.servlet.ServletRequest:
javax.servlet.http.HttpServletRequest
Methods for Scope Objects

 Object getAttribute(String name)

 void setAttribute(String name, Object value)

 Enumeration getAttributeNames();
Example: Getting Attribute Value
from ServletContext
ServletContext context=getServletContext();

Context.setAttribute(“ContextAttribute” , “SomeVal”);

String val=
(String)context.getAttribute("ContextAttribute");

Vous aimerez peut-être aussi