Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

What is a Servlet?

• Servlets are Java programs that can be run


dynamically from a Web Server
• Servlets are a server-side technology
• A Servlet is an intermediating layer between
an HTTP request of a client and the data
stored on the Web server

1
A Servlet in Web Application

2
What can Servlets do?
• Read data sent by the user (e.g., form data)
• Look up other information about the request in the
HTTP request (e.g. authentication data, cookies,
etc.)
• Generate the result (may do this by talking to a
database, file system, etc.)
• Format the result as a document (e.g., convert it
into HTML format)
• Set the appropriate HTTP response parameters
(e.g. cookies, content-type, etc.)
3
• Send the resulting document to the user
Servlet Terminology
• HTTP
• Http Request Methods
• Difference between Get and Post
• Anatomy of Get Request
• Anatomy of Post Request
• Content Type
• Server (Web And Application)
• Container
• Servlet Interface
4
HTTP
• HTTP (Hyper Text Transfer Protocol)
• Http is the protocol that allows web servers and browsers to
exchange data over the web.
• It is a request response protocol.
• Http uses reliable TCP connections by default on TCP port
80.
• It is stateless means each request is considered as the new
request.
• Version : 1.0/1.1

5
HTTP

6
HTTP
• HTTP Request Methods:

GET
• Asks to get the resource at the requested URL.
POST
• Asks the server to accept the body info attached. It is like GET request
with extra info sent with the request.

7
HTTP GET request

8
HTTP POST request

9
HTTP
GET POST

1) In case of Get request, In case of post request, large


only limited amount of data can be amount of data can be sent
sent because data is sent in because data is sent in body.
header.

2) Get request is not Post request is secured because


secured because data is exposed data is not exposed in URL bar.
in URL bar.
3) Get request can be bookmarked Post request cannot
be bookmarked
4) Get request is idempotent. It Post request is non-idempotent
means second request will be
ignored until response of first
request is delivered.

5) Get request is more efficient and Post request is less efficient and
used more than Post used less than get.
10
HTTP Request Methods

• POST - application data sent in the request


body
• GET - application data sent in the URL
• HEAD - client sees only header of response
• PUT - place documents directly on server
• DELETE - opposite of PUT
• TRACE - debugging aid
• OPTIONS - list communication options

11
HTTP Request Packets

• Sent from client to server


• Consists of HTTP header
- header is hidden in browser environment
- contains:
• content type / mime type
• content length
• user agent - browser issuing request
• content types user agent can handle
• and a URL
HTTP Response Packets

Sent by server to client browser


• Status Line
• Headers
• Content-Encoding:
• Content-Length:
• Content-Type:
• Last-Modified:

• Body – content (usually html)


Status Header

Status Line: “HTTP/1.0 sp code”


• Codes:
- 1xx - reserved for future use
- 2xx - successful, understood and accepted
- 3xx - further action needed to complete
- 4xx - bad syntax in client request
- 5xx - server can’t fulfill good request
Content Type
• Content Type is also known as MIME (Multipurpose internet Mail
Extension) Type. It is a HTTP header that provides the description
about what are you sending to the browser.
There are many content types:
• text/html
• text/plain
• application/msword
• application/vnd.ms-excel
• application/jar
• application/pdf
• application/octet-stream
• application/x-zip
• images/jpeg
• video/quicktime etc. 15
Status Codes

• 200 OK • 401 unauthorized


• 201 created • 403 forbidden
• 202 accepted • 404 not found
• 204 no content • 500 int. server error
• 301 moved perm. • 501 not impl.
• 302 moved temp • 502 bad gateway
• 304 not modified • 503 svc not avail
• 400 bad request
Server

It is a running program or software that


provides services.
There are two types of servers:
• Web Server
• Application Server

17
Server
• Web Server
• Web server contains only web or servlet container. It can be used for
servlet, jsp, struts etc. It can't be used for EJB( development
architecture for building highly scalable and robust enterprise level
applications)
• Examples of Web Servers are: Apache Tomcat and Resin.
• Application Server
• Application server contains Web and EJB containers. It can be used for
servlet, jsp, struts, EJB etc.
• Example of Application Servers are:
• JBoss Open-source server from JBoss community.
• Glassfish provided by Sun Microsystem. Now acquired by Oracle.
• Weblogic provided by Oracle. It more secured.
• Websphere provided by IBM. 18
Container
• Servlet Container : A servlet container (also called a servlet
engine) is a separate module used by the web server to
load and run servlets.

• The servlet container


• Creates servlet instances
• Loads and unloads servlets
• Creates and manages request and response objects
• Performs other servlet management tasks.

19
Servlet Container Architecture

HTTP Request HTTP Servlet


Servlet
Browser HTTP Response Container
Server
Static
Content
Servlet Architecture

• Servlet is the interface


which all servlets will implement.
Usually, servlets program is
Implemented by extending
HttpServlet class
Key Classes and Interfaces of
the Servlet API

javax.servlet java.servlet.http
«interface» Servlet
«abstract» GenericServlet «abstract» HttpServlet

«interface» ServletRequest «interface»


HttpServletRequest
«interface»ServletResponse «interface»HttpServletRespon
se
«interface» ServletConfig
«interface»ServletContext
---------- «interface» HttpSession
ServletException Cookie
22
javax.servlet package

• Interface Servlet: The main interface that every servlet must implement.
It defines the key methods that a servlet container calls to control the
servlet.
• Abstract class GenericServlet :This abstract class can be used as the
starting point for implementing servlets. In particular, it implements all
the methods of the Servlet interface except the service() method. This
abstract class also implements the ServletConfig interface which allows
the servlet container to pass information to the servlet.
• interface ServletRequest :This interface provides the methods to extract
information from a client request
• interface ServletResponse :This interface provides the methods to
create and send an appropriate response to a client request.

23
javax.servlet package

• interface ServletConfig :This interface which allows the servlet container


to pass information to a servlet.
• interface ServletContext :This interface allows the servlet to
communicate with its container.
• class ServletException : A general exception class to signal servlet
runtime errors.

24
javax.servlet.http package

• abstract class HttpServlet : This abstract class extends the


GenericServlet class and is used for implementing HTTP servlets, i.e.
servlets which use HTTP for requests and responses. In particular, it
provides stubs for the doHttpRequestMethodName() methods which
correspond to the HTTP method used in the request (GET, POST,
HEAD, etc.). A concrete servlet can override the appropriate.
• interface HttpServletRequest : This interface extends the
ServletRequest interface to handle HTTP requests.
• interface HttpServletResponse :This interface extends the
ServletResponse interface to create and send an appropriate HTTP
response to an HTTP request.

25
javax.servlet.http package

• interface HttpSession: This interface 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. class Cookie This class provides support
for cookies to be used in requests and responses

26
javax.servlet.http package

• Methods in the HttpServlet class that handle client


requests take two arguments:

- An HttpServletRequest object, which encapsulates


the data from the client. It provides access to HTTP
header data and obtain the arguments that the client
sent as part of the request.

- An HttpServletResponse object, which encapsulates


the response to the client. It returns data to the user
by Writer (plain text) or ServletOutputStream (binary).
Hello World(1) Servlet Example
• // Import required java libraries
• import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;

• // Extend HttpServlet class
• public class HelloWorld extends HttpServlet {
• private String message;
• public void init() throws ServletException
• {
• // Do required initialization
• message = "Hello World";
• }

28
Hello World (1) Servlet Example
public void doGet(HttpServletRequest request,
• HttpServletResponse response) throws ServletException,
IOException {
• // Set response content type
• response.setContentType("text/html");
• // Actual logic goes here.
• PrintWriter out = response.getWriter();
• out.println("<h1>" + message + "</h1>");
• }
• public void destroy()
• {
• // do nothing.
• }
• }
29
Writing Hello World (2)
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();

30
Writing Hello World(2)
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);
}
}

31
Handling Form Data
<HTML>
<HEAD>
<TITLE> INTRODUCTION</TITLE>
<HEAD>
<BODY>
<FORM METHOD=GET ACTION=“/servlet/Hello”>
What is your name?
<INPUT TYPE=TEXT NAME=“name”<P>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
32
Writing Hello World(3)
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();
String name=req.getParameter(“name”);
33
Writing Hello World(3)
out.println("<html>");
out.println("<head><title>Hello, “+name+”</title></head>")
out.println("<body>");
out.println(“Hello,” +name);
out.println("</body></html>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}

34
Servlet Life Cycle

35
Servlet Life Cycle
Generic Servlet & HTTP Servlet

GenericServlet
Client
request

Server service ( )
response

HTTPServlet
Browser

request doGet( )
HTTP service ( )
Server
response doPost( )
GenericServlet - Methods

• void init(ServletConfig config)


- Initializes the servlet. This method is called once when the Servlet is
loaded into the Servlet engine, before the Servlet is asked to
process its first request
• void service(ServletRequest req, ServletResponse res)
- Carries out a single request from the client. . Multiple threads (one
per request) can execute this method in parallel so it must be thread
safe.
• void destroy()
- Cleans up whatever resources are being held (e.g., memory, file
handles, threads) This method is called once just before the Servlet
is unloaded and taken out of service.
• ServletConfig getServletConfig()
- Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.
• String getServletInfo()
- Returns a string containing information about the servlet, such as its
author, version, and copyright.
HttpServlet - Methods
• void doGet (HttpServletRequest request,
HttpServletResponse response)
–handles GET requests
• void doPost (HttpServletRequest request,
HttpServletResponse response)
–handles POST requests
• void doPut (HttpServletRequest request,
HttpServletResponse response)
–handles PUT requests
• void doDelete (HttpServletRequest request,
HttpServletResponse response)
– handles DELETE requests
Steps to Running a Servlet

• Create a directory structure under Tomcat


for your application.
• Write the servlet source code.
• Compile your source code.
• Deploy the servlet
• Run Tomcat
• Call your servlet from a web browser
Directory Structure

41
Compile the Servlet

• Compile the Servlet class


• The resulting TestingServlet.class file should
go under myApp/WEB-INF/classes
Deploy the Servlet

• In the Servlet container each application is


represented by a servlet context
• each servlet context is identified by a unique path
prefix called context path
- For example our application is identified by /myApp
which is a directory under webapps.
• The remaining path is used in the selected context
to find the specific Servlet to run, following the
rules specified in the deployment descriptor.
Deployment Descriptor
• The deployment descriptor is a XML file called web.xml
that resides in the WEB-INF directory whitin an
application.
<web-app xmlns=http://java.sun.com/xml/ns/j2ee……>

<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Testing</servlet-name>
<url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>

</web-app>
Run the Servlet

• To execute your Servlet, type the following


URL in the Browser’s address field:
• http://localhost/myApp/servlet/myServlet
How Servlet works?
• It is important to learn how servlet works for understanding the servlet
well. Here, we are going to get the internal detail about the first servlet
program.
• The server checks if the servlet is requested for the first time.
• If yes, web container does the following tasks:
• loads the servlet class.
• instantiates the servlet class.
• calls the init method passing the ServletConfig object
• else
• calls the service method passing request and response objects
• The web container calls the destroy method when it needs to remove
the servlet such as at time of stopping server or undeploying the
project.
46
HTTP

47
(1) Request Line
• GET
http://localhost:8080/horoscope/SimpleHoroscope/index.html?parameter
=value&also=another HTTP/1.0
• Host: localhost:8080
• Context path:/horoscope
• Servlet path:/SimpleHoroscope
• Requsted URI:/horoscope/SimpleHoroscope
• Query: parameter=value&also=another
• Requested URL : http://localhost:8080/horoscope/SimpleHoroscope
• Extra path information: index.html

48
(2)Client HTTP Request Headers
Header Description

Accept This header specifies the MIME types that the browser or
other clients can handle. Values
of image/png or image/jpeg are the two most common
possibilities.

Accept-Charset This header specifies the character sets the browser can use
to display the information. For example ISO-8859-1.

Accept-Encoding This header specifies the types of encodings that the browser
knows how to handle. Values of gzip or compress are the
two most common possibilities.

Accept-Language This header specifies the client's preferred languages in case


the servlet can produce results in more than one language.
For example en, en-us, ru, etc.
49
(2)Client HTTP Request
Headers
Header Description

Authorization This header is used by clients to identify themselves when


accessing password-protected Web pages.

Connection This header indicates whether the client can handle persistent
HTTP connections. Persistent connections permit the client or
other browser to retrieve multiple files with a single request. A
value of Keep-Alivemeans that persistent connections should
be used
Content-Length This header is applicable only to POST requests and gives
the size of the POST data in bytes.
Cookie This header returns cookies to servers that previously sent
them to the browser.
Host This header specifies the host and port as given in the original
URL
50
(2)Client HTTP Request
Headers
Header Description

If-Modified-Since This header indicates that the client wants the page only if it
has been changed after the specified date. The server sends
a code, 304 which means Not Modified header if no newer
result is available.

If-Unmodified- This header is the reverse of If-Modified-Since; it specifies


Since that the operation should succeed only if the document is
older than the specified date.

Referer This header indicates the URL of the referring Web page. For
• . example, if you are at Web page 1 and click on a link to Web
page 2, the URL of Web page 1 is included in the Referer
header when the browser requests Web page 2.
•User-Agent This header identifies the browser or other client making the
request and can be used to return different content to different
51
types of browsers.
Methods to read HTTP Request Line and
Request Headers

Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or an
empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing all of
the values the given request parameter has, or
null if the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a
String, or null if the parameter does not exist.
Methods to read HTTP Request Line and
Request Headers

Cookie[] getCookies()
Returns an array containing all of the Cookie objects
the client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with which\thi
request was made, for example, GET, POST, or PUT.

java.lang.String getQueryString()
Returns the query string that is contained in the
request URL after the path.
HttpSession getSession()
Returns the current session associated with this
request, or if the request does not have a session,
creates one.
Methods to read HTTP Request Line and
Request Headers

int getContentLength() Returns the length, in bytes, of the


request body and made available by the input stream,
or -1 if the length is not known.

int getIntHeader(String name) Returns the value of


the specified request header as an int.
int getServerPort() Returns the port number on which this
request was received.
Enumeration getHeaderNames() Returns an enumeration of all the
header names this request contains.
Retrieving Information

• about servlet init parameters


• about context init parameters
• about server
• about client machine
• about user
• about path
• about Request Parameters
Retrieving Information about servlet
init parameters
• ServletConfig Interface

• An object of ServletConfig is created by the web container for each


servlet. This object can be used to get configuration information from
web.xml file.

• If the configuration information is modified from the web.xml file, we


don't need to change the servlet. So it is easier to manage the web
application if any specific content is modified from time to time.

• Advantage of ServletConfig
• The core advantage of ServletConfig is that you don't need to edit the
servlet file if information is modified from the web.xml file.
56
Retrieving Information about servlet
init parameters
• Methods of ServletConfig interface
• public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
• public Enumeration getInitParameterNames():Returns an
enumeration of all the initialization parameter names.

• Syntax of getServletConfig() method


• public ServletConfig getServletConfig();

• Example of getServletConfig() method


• ServletConfig config=getServletConfig();
• //Now we can call the methods of ServletConfig interface
57
Retrieving Information about servlet
init parameters
Example of ServletConfig to get initialization parameter

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
thows ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");
out.print("Driver is: "+driver);
out.close();
}
}
58
web.xml
• <web-app>
• <servlet>
• <servlet-name>DemoServlet</servlet-name>
• <servlet-class>DemoServlet</servlet-class>
• <init-param>
• <param-name>driver</param-name>
• <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
• </init-param>
• </servlet>
• <servlet-mapping>
• <servlet-name>DemoServlet</servlet-name>
• <url-pattern>/servlet1</url-pattern>
• </servlet-mapping>
• </web-app> 59
Retrieving Information about
context init parameters
• ServletContext Interface
• An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration
information from web.xml file. There is only one ServletContext object
per web application.
• If any information is shared to many servlet, it is better to provide it from
the web.xml file using the<context-param> element.

• Advantage of ServletContext
• Easy to maintain if any information is shared to all the servlet, it is
better to make it available for all the servlet. We provide this information
from the web.xml file, so if the information is changed, we don't need to
modify the servlet. Thus it removes maintenance problem.
60
Retrieving Information about
context init parameters
• Usage of ServletContext Interface

• The object of ServletContext provides an interface between the


container and servlet.
• The ServletContext object can be used to get configuration information
from the web.xml file.
• The ServletContext object can be used to set, get or remove attribute
from the web.xml file.
• The ServletContext object can be used to provide inter-application
communication.

61
Retrieving Information about
context init parameters
• Commonly used methods of ServletContext interface
• public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
• public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters.

• How to get the object of ServletContext interface


• getServletContext() method of ServletConfig interface returns the object
of ServletContext.
• getServletContext() method of GenericServlet class returns the object of
ServletContext.

• Syntax of getServletContext() method


• public ServletContext getServletContext()
62
Retrieving Information about
context init parameters
• Example of getServletContext() method
• //We can get the ServletContext object from ServletConfig object
• ServletContext application=getServletConfig().getServletContext();

• //Another convenient way to get the ServletContext object
• ServletContext application=getServletContext();

63
Retrieving Information about
context init parameters
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String driverName=context.getInitParameter("dname");
pw.println("driver name is="+driverName);
pw.close(); }}

64
web.xml
• <web-app>
• <servlet>
• <servlet-name>sonoojaiswal</servlet-name>
• <servlet-class>DemoServlet</servlet-class>
• </servlet>
• <context-param>
• <param-name>dname</param-name>
• <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
• </context-param>
• <servlet-mapping>
• <servlet-name>sonoojaiswal</servlet-name>
• <url-pattern>/context</url-pattern>
• </servlet-mapping>
• </web-app>
65
Retrieving Information About the Server
String getServerName()
Returns the host name of the server that received the
request
int getServerPort()
Returns the port number on which this request was
received.
String ServletContext.getServerInfo()
Returns information about the server software and its
attributes

A servlet can display this information to a client, use it to


customize its behavior based on a particular server
package, or even use it to explicitly restrict the machines
on which the servlet will run.
Retrieving Information about the Client
Machine

String getRemoteAddr()
Returns the Internet Protocol (IP) address of the
client or last proxy that sent the request.
String getRemoteHost()
Returns the fully qualified name of the client or
the last proxy that sent the request.
int getRemotePort()
Returns the Internet Protocol (IP) source port of the
client or last proxy that sent the request.

This information can be used for logging access data,


associating information with individual users, or restricting
access to certain clients.
Retrieving Information About the User

String getRemoteUser()
Returns the login of the user making this request, if
the user has been authenticated, or null if the user
has not been authenticated.

With the remote user’s name, a servlet can save information


about each client.
Over the long term, it can remember each individual’s
preferences. For the short
term, it can remember the series of pages viewed by the client
and use them to
add a sense of state to a stateless HTTP protocol
Retrieving Information About the Path

java.lang.String getPathInfo()
Returns any extra path information associated with the
URL the client sent when it made this request.
java.lang.String getPathTranslated()
Returns any extra path information after the servlet
name but before the query string, and translates it to a
real path.

Use : This extra path information is used to indicate a file on the


server that the servlet should use for something.

An example URL looks like this:


http://server:port/servlet/ViewFile/index.html

Extra path information: "/index.html"

Translation of path information


Retrieving Information
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class RetrieveInfo extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse
res) throws IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();

//Retrieving Information About the Server


out.println("req.getServerName(): " + req.getServerName());.

out.println("req.getServerPort(): " + req.getServerPort());

out.println("getServletContext().getServerInfo(): " +
getServletContext().getServerInfo());
Retrieving Information
//Retrieving Information about the Client Machine
out.println("req.getRemoteAddr(): " + req. getRemoteAddr());
out.println(“req.getRemoteHost(): " + req. getRemoteHost());

//Retrieving Information about the User


out.println("req.getRemoteUser(): " + req.getRemoteUser();

//Retrieving Information about the Path


if (req.getPathInfo() != null)
{
out.println("The file \"" + req.getPathInfo() + "\"");
out.println("Is stored at \"" + req.getPathTranslated() + "\"");
}
Retrieving Information
req.getServerName(): localhost
req.getServerPort(): 8080
getServletContext().getServerInfo(): JavaWebServer/1.1.1
req.getRemoteAddr():"192.26.80.118
req.getRemoteHost():dist.engr. sgi.com
req.getRemoteUser():JHunter
The file “index.html”
Is stored at "C:\JavaWebServer1.1.1\public_html\dict\index.html”
Retrieving Information About Request
Parameteres

Enumeration getParameterNames()
Returns an Enumeration of String objects
containing the names of the parameters contained
in this request.
String[] getParameterValues(name)
Returns an array of string objects containing all of
the values the given request parameter has,
or null if the parameter does not exist
Retrieving Information Request Parameters
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ParameterSnoop extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("Query String:");
out.println(req.getQueryString());
out.println();
out.println("Request Parameters:");
}
Retrieving Information Request
Parameters
Enumeration enum = req.getParameterNames();
while (enum.hasMoreElements()) {
String name = (String) enum.nextElement();
String values[] = req.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
out.println(name + " (" + i + "): " + values[i]);
}
}
}
}

You might also like