0% found this document useful (0 votes)
30 views39 pages

Servlets JSP

Uploaded by

jagruti.patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views39 pages

Servlets JSP

Uploaded by

jagruti.patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Servlets & JSP

SACHIN KHARADE
Servlet
• Servlet is used to create web applications.
Servlet uses Java language to create web
applications.
• Web applications are helper applications that
resides at web server and build dynamic web
pages. A dynamic page could be anything like a
page that randomly chooses picture to display
or even a page that displays the current time.

SACHIN KHARADE
Types of Servlet
• There are two main servlet types, generic and HTTP

• Generic servlets

It extends javax.servlet.GenericServlet. It is protocol


independent servlet. Generic Servlet is a base class servlet from
which all other Servlets are derived. Generic Servlet supports for
HTTP, FTP and SMTP protocols. It implements the Servlet and
ServletConfig interface. It has only init() and destroy() method of
ServletConfig interface in its life cycle. It also implements the log
method of ServletContext interface.

SACHIN KHARADE
Types of Servlet (cont’d…)
• HTTP servlets

It extend javax.servlet.HttpServlet. HTTPServlet is HTTP


dependent servlet. The HTTP protocol is a set of rules that allows
Web browsers and servers to communicate. When Web browsers
and servers support the HTTP protocol, Java-based web
applications are dependent on HTTP Servlets. HttpServlet is
Extended by Generic Servlet. It provides an abstract class for the
developers for extend to create there own HTTP specific servlets.

SACHIN KHARADE
Servlet Life Cycle
• The life cycle of a servlet is controlled by the container in
which the servlet has been deployed. When a request is
mapped to a servlet, the container performs the
following steps.
• If an instance of the servlet does not exist, the Web
container
– Loads the servlet class.
– Creates an instance of the servlet class.
– Initializes the servlet instance by calling the init method.
Initialization is covered in Initializing a Servlet.
• Invokes the service method, passing a request and
response object.
• If the container needs to remove the servlet, it finalizes
the servlet by calling theSACHIN
servlet's
KHARADE
destroy method.
Servlet life cycle methods
The init() method
• The init method is designed to be called only once. It is called when the servlet is first
created. So, it is used for one-time initializations, just as with the init method of
applets.
• The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
• When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
• The init method definition looks like this:

public void init() throws ServletException


SACHIN KHARADE
{ // Initialization code... }
Servlet life cycle methods
The service() method
• The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming
from the client( browsers) and to write the formatted response back to the
client.
• Each time the server receives a request for a servlet, the server spawns a new
thread and calls service. The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
• Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException
SACHIN KHARADE
{ }
Servlet life cycle methods
The destroy() method
• The destroy() method is called only once at the end of the life
cycle of a servlet.
• This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit
counts to disk, and perform other such cleanup activities.
• After the destroy() method is called, the servlet object is
marked for garbage collection.
• The destroy method definition looks like this:
public void destroy()
{ // Finalization code... } SACHIN KHARADE
Servlet Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.
 First the HTTP requests coming to the server are delegated to the servlet
container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.

SACHIN KHARADE
Http Request Methods

Every request has a header that tells the status of the client. There are
many request methods. Get and Post requests are mostly used.

GET Asks to get the resource at the requested URL.

Asks the server to accept the body info attached. It is like


POST
GET request with extra info sent with the request.

SACHIN KHARADE
The doGet() Method
A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.

public void doGet(HttpServletRequest request,


HttpServletResponse response) throwsServletException,IOException
{
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as
the METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request,


HttpServletResponse response) throwsServletException,IOException
{
// Servlet code
SACHIN KHARADE
}
Sample Code for Hello World

SACHIN KHARADE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Public class HelloWorld extends HttpServlet
{
String message;
publicvoid init() throws ServletException
{
message ="Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
out.println("<h1>"+ message +"</h1>");
}
public void destroy()
{ }
}
SACHIN KHARADE
Servlet Deployment
By default, a servlet application is located at the path
<Tomcat-installation-directory>/webapps/ROOT
and the class file would reside in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes

Let us copy HelloWorld.class into


<Tomcat-installation-directory>/ webapps/ ROOT/ WEB-INF/classes
and create following entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in
web.xml file. SACHIN KHARADE
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of
some elements that is used in the above web.xml file. The elements are
as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of


the servlet.

<servlet-class> is sub element of <servlet> represents the class of


the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map


the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is


used at client side to invoke the servlet.
SACHIN KHARADE
SACHIN KHARADE
SendRedirect in servlet
 The sendRedirect() method of HttpServletResponse interface
can be used to redirect response to another resource, it may be
servlet, jsp or html file.

 It accepts relative as well as absolute URL.

 It works at client side because it uses the url bar of the browser
to make another request. So, it can work inside and outside the
server.

SACHIN KHARADE
Difference between forward() and sendRedirect()
method
There are many differences between the forward() method of
RequestDispatcher and sendRedirect() method of HttpServletResponse
interface. They are given below:

forward() method sendRedirect() method

The forward() method works at The sendRedirect() method works


server side. at client side.

It sends the same request and It always sends a new request.


response objects to another
servlet.

It can work within the server only. It can be used within and outside
the server.

Example: Example:
request.getRequestDispacher("ser response.sendRedirect("servlet2");
vlet2").forward(request,response);

SACHIN KHARADE
Syntax of sendRedirect() method

public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method

response.sendRedirect("http://www.javatpoint.com");

SACHIN KHARADE
example of sendRedirect method in servlet

SACHIN KHARADE
DemoServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet


{

public void doGet(HttpServletRequest req,HttpServletResponse res) throws Servlet


Exception,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

response.sendRedirect("http://www.google.com");

pw.close();
}
}
SACHIN KHARADE
index.html

<!DOCTYPE html>
<html>
<head>
<title>sendRedirect example</title>
</head>
<body>

<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>

</body>
</html>

SACHIN KHARADE
MySearcher.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MySearcher extends HttpServlet


{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}

SACHIN KHARADE
Session and Cookies
Session simply means a particular interval of time.

The term user session refers to a series of user application


interactions that are tracked by the server. Sessions are used for
maintaining user specific state, including persistent objects (like
handles to database result sets) and authenticated user identities,
among many interactions. For example, a session could be used to
track a validated user login followed by a series of directed
activities for a particular user.

The session itself resides in the server. For each request, the client
transmits the session ID in a cookie or, if the browser does not
allow cookies, the server automatically writes the session ID into
the URL.

SACHIN KHARADE
Session and Cookies (cont’d…)

A cookie is a small collection of information that can be


transmitted to a calling browser, which retrieves it on each
subsequent call from the browser so that the server can recognize
calls from the same client. A cookie is returned with each call to
the site that created it, unless it expires.

Sessions are maintained automatically by a session cookie that is


sent to the client when the session is first created. The session
cookie contains the session ID, which identifies the client to the
browser on each successive interaction.

SACHIN KHARADE
Cookie class
javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

constructs a cookie with a specified


Cookie(String name, String value) name and value.

SACHIN KHARADE
Useful Methods of Cookie class
Following are given some commonly used methods of the Cookie class.

Method Description
Sets the maximum age of the
public void setMaxAge(int expiry)
cookie in seconds.

Returns the name of the cookie.


public String getName() The name cannot be changed after
creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

SACHIN KHARADE
Other methods required for using Cookies

1.For adding cookie or getting the value from the cookie, we need
some methods provided by other interfaces. They are:

1. public void addCookie(Cookie ck)

method of HttpServletResponse interface is used to add cookie in


response object.

2. public Cookie[] getCookies()

method of HttpServletRequest interface is used to return all the


cookies from the browser.

SACHIN KHARADE
Creating Cookie
Cookie ck=new Cookie("user","sonu");//creating cookie object
response.addCookie(ck);//adding cookie in the response

Deleting Cookie
It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie


ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
}
SACHIN KHARADE
Session Tracking in Servlets

Session Tracking is a way to maintain state (data) of an user. It is also known


as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as
the new request. So we need to maintain the state of an user to recognize to
particular user.

HTTP is stateless that means each request is considered as the new request.

Session Tracking Techniques


There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
SACHIN KHARADE
SACHIN KHARADE
Servlet Chaining
In many servers that support servlets, a request can be handled by a
sequence of servlets. The request from the client browser is sent to the
first servlet in the chain. The response from the last servlet in the chain is
returned to the browser. In between, the output from each servlet is
passed (piped) as input to the next servlet, so each servlet in the chain has
the option to change or extend the content

SACHIN KHARADE
Figure Servlet chaining
Servlet Filters
When a servlet converts one type of content into another, the technique is
called filtering .
A filter is an object that is invoked at the preprocessing and postprocessing of a
request.
It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.

SACHIN KHARADE
Defining Filter

We can define filter same as servlet. Let's see the elements of


filter and filter-mapping.
<web-app>

<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>

<filter-mapping>
<filter-name>...</filter-name>
<url-pattern>...</url-pattern>
</filter-mapping>

</web-app>
SACHIN KHARADE
Example of authenticating user using filter

SACHIN KHARADE
index.html

<form action="servlet1">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>

<input type="submit" value="login">

</form>

SACHIN KHARADE
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;

public class MyFilter implements Filter{


public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {

PrintWriter out=resp.getWriter();

String password=req.getParameter("password");
if(password.equals("admin")){
chain.doFilter(req, resp);//sends request to next resource
}
else{
out.print("username or password error!");
RequestDispatcher rd=req.getRequestDispatcher("index.html");
rd.include(req, resp);
}
}
public void destroy() {}
} SACHIN KHARADE
AdminServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class AdminServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("welcome ADMIN");
out.close();
}
}

SACHIN KHARADE
web.xml

<web-app>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>AdminServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>

</web-app>
SACHIN KHARADE

You might also like