Académique Documents
Professionnel Documents
Culture Documents
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.
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
For example :
HTTP/1.0 200 OK
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 .
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.*;
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 :
service()
Called in a new thread by server for each request.
Dispatches to doGet, doPost, etc.
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.*;
HttpServletResponse
getParameter( “paramName” )
3 parts
Scheme or protocol.
DNS name of the host.
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()
Enumeration getParameterNames()
HTTP Request
Client sends a request
Request method, URI, and protocol version.
Request headers
A blank line.
host : localhost:8080
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.
– web.xml :
Web application deployment descriptor that contains meta-data for
the web application.
– 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.
<!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>
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 {
<context-param>
<param-name>support-email</param-name>
<param-value>pqr@mycompany.com</param-value>
</context-param>
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 ?
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”);
• It calls :
RequestDispatcher view =
request.getRequestDispatcher(“abc.jsp”);
view.forward(request,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
{
RequestDispatcher rd =
req.getRequestDispatcher("../login.html");
rd.forward(req, res);
return;
}
}
Including another Web
Resource
When to Include another Web
resource?
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
Enumeration getAttributeNames();
Example: Getting Attribute Value
from ServletContext
ServletContext context=getServletContext();
Context.setAttribute(“ContextAttribute” , “SomeVal”);
String val=
(String)context.getAttribute("ContextAttribute");