You are on page 1of 33

PRESENTATION ON

Servlets and JSP


Presented By:
Prof. Kautkar Rohit Anil

Assistant Professor

Computer Engineering,
Sandip Institute of Polytechnic, Nashik
Contents
Introduction to Servlets

Motivation behind the servlets

Types of Servlets
Generic Servlets
HTTP Servlets

Servlet LifeCycle

Using Servlet Request and Response


Contents
The Servlet API

The javax.servlet package


The javax.servlet.http package

Handling HTTP Request and Responses

Servlet Redirection

Basic Concepts of Sessions, Cookies and Session


Tracking
Introduction to Servlet
Web Browsers and Servers?
What are Servlets?
Basically WebPages generated by web server in
response to the request send by the clients.

Java Classes that Extends functionality of Server

Provide advantages compare to other technologies


Static Webpages– URL, MIME, HTML

Dynamic Web Pages– Contents on the fly… Example?


Introduction to Servlet
Web Browsers and Servers Communication?

CGI?

Common Gateway interface

Provide separate process for each HTTP Request

Can Open connection to one or more DB

Languages: C, C++, Perl, Python etc.


Advantages to Servlet
Advantages of Servelts?

Performance is Better
Execute within Server Space
No need to create separate process
Platform independent as Java compiled
Supports several Web Browsers
JSM implements security constraints to protect
resources on Server Machine
All Java Libraries are available in Servlet
Types of Servlet

Servlets

User to Implements User to Implements


Basic Lifecycle of Generic HTTP web Based
Servlets Servlets Servlets
Applications

Protocol Built-in Support


Independent for Protocols
Generic Servlet HTTP Servlet

Javax.servlet.GenericServlet package Javax.servlet.http package

Uses service() method doPost(), doGet() methods

Do not use any protocol Uses protocol


Servlet Lifecycle
Easy to understand

Based on Three methods through which each servlet Pass

1.Init()
2.Service()
3.Destroy()
Servlet Lifecycle

Init() Service() Destroy()

• When • Perform • When


Servlet Task Servlet
Created Deleted
Example Scenario of Sevlet
User will Enter URL

Browser Generate HTTP Request and sends to appropriate


Server

Server Receive Request and Maps to Servlet

Servlet dynamically retrived and loaded in to server Space

Servlet invokes init() method– when first time loaded into


memory of server
Example Scenario of Sevlet
Initialization parameters passed to servlet for configuration

Now, Service() method is invoked

Service() for processing HTTP Requests and based on


which For Generating Responses

Servlet remains in Server Space for other clients

Each Request invokes service() method


Example Scenario of Sevlet
Finally server takes decision to unload it from memory

Invokes destroy() for deleting it

Now, all objects are thrown to Garbage collector


Example Scenario of Sevlet
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
The Servlet API

javax.servlet and javax.servlet.http package to handle


Servlet
Interface Description
Servlet Declares life cycle methods for a
servlet.
ServletConfig Allows servlets to get initialization
parameters.
ServletContext Enables servlets to log events and
access information about their
environment.
ServletRequest Used to read data from a client request.

ServletResponse Used to write data to a client response


Interface Description
HttpServletRequest Enables servlets to read data from an
HTTP request
HttpServletResponse Enables servlets to write data to an
HTTP response.
HttpSession Allows session data to be read and
written.

Cookie Allows state information to be stored on


a client
machine.

HttpServlet Provides methods to handle HTTP


requests and
responses
Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods

A servlet developer typically overrides one of these


methods

These methods are -- doDelete( ),


 doGet( ),
doOptions( ),
 doPost( ),
 doPut( ),
doTrace( ).
1. <html>
2. <body>
3. <center>
4. <form name="Form1”
action="http://localhost:8080/servlet/ColorGetServlet">
5. <B>Color:</B>
6. <select name="color" size="1">
7. <option value="Red">Red</option>
8. <option value="Green">Green</option>
9. <option value="Blue">Blue</option>
10. </select>
11. <br><br>
12. <input type=submit value="Submit">
13. </form>
14. </body>
15. </html>
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;

4. public class ColorGetServlet extends HttpServlet


5. {
6. public void doGet(HttpServletRequest request,
7. HttpServletResponse response)
8. throws ServletException, IOException {
9. String color = request.getParameter("color");
10. response.setContentType("text/html");
11. PrintWriter pw = response.getWriter();
12. pw.println("<B>The selected color is: ");
13. pw.println(color);
14. pw.close();
15. }
16. }
1. <html>
2. <body>
3. <center>
4. <form name="Form1“ method="post“
action="http://localhost:8080/servlet/ColorPostServlet">
5. <B>Color:</B>
6. <select name="color" size="1">
7. <option value="Red">Red</option>
8. <option value="Green">Green</option>
9. <option value="Blue">Blue</option>
10. </select>
11. <br><br>
12. <input type=submit value="Submit">
13. </form>
14. </body>
15. </html>
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class ColorPostServlet extends HttpServlet
5. {
6. public void doPost(HttpServletRequest request,
7. HttpServletResponse response)
8. throws ServletException, IOException {
9. String color = request.getParameter("color");
10. response.setContentType("text/html");
11. PrintWriter pw = response.getWriter();
12. pw.println("<B>The selected color is: ");
13. pw.println(color);
14. pw.close();
15. }
16. }
Using Cookies
Small piece of information

Stored by server on client browser

Stores info like date, time, userid, preferences etc.


Using Cookies
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class AddCookieServlet extends HttpServlet
5. {
6. public void doPost(HttpServletRequest request,
7. HttpServletResponse response)
8. throws ServletException, IOException {
9. String data = request.getParameter("data"); // Get parameter from HTTP
request
10. Cookie cookie = new Cookie("MyCookie", data); // Create cookie
11. response.addCookie(cookie); // Add cookie to HTTP response
12. response.setContentType("text/html"); // Write output to browser
13. PrintWriter pw = response.getWriter();
14. pw.println("<B>MyCookie has been set to");
15. pw.println(data);
16. pw.close();
17. }
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class GetCookiesServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. throws ServletException, IOException
7. {
8. Cookie[] cookies = request.getCookies();
9. response.setContentType("text/html");
10. PrintWriter pw = response.getWriter();
11. pw.println("<B>");
12. for(int i = 0; i < cookies.length; i++) {
13. String name = cookies[i].getName();
14. String value = cookies[i].getValue();
15. pw.println("name = " + name +" value = " + value);
16. }
17. pw.close();
18. }
19. }
Session Tracking
HTTP is a stateless protocol

it is necessary to save state information so that information can


be collected from several interactions between a browser and a
Server

Sessions are Solutions

Created using getSession( ) method of HTTPServletRequest


Session Tracking
It Supports,

 putValue( )
getValue( )
getValueNames( )
removeValue( )
1. import java.io.*;
2. import java.util.*;
3. import javax.servlet.*;
4. import javax.servlet.http.*;
5. public class DateServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. HttpSession hs = request.getSession(true);
9. response.setContentType("text/html");
10. PrintWriter pw = response.getWriter();
11. pw.print("<B>");
12. Date date = (Date)hs.getValue("date");
13. if(date != null) {
14. pw.print("Last access: " + date + "<br>");
15. }
16. date = new Date();
17. hs.putValue("date", date);
18. pw.println("Current date: " + date);
19. }
Servlet Redirection
It is based on the status code of headers

Sending instructions to client for redirection

Situations in which redirection is required are

Document moved
Load balancing
randomization

setHeader(“Location=www.google.com”);
Servlet chaining
Generally one servlet is used to create web page

In servlet chaining, contents are created by multiple servlets

Many servlets used in chain format

Request to First Servlet of chain

Responser from last Servlet in chain


Thank you.
Prof. Kautkar Rohit A.(M.Tech)
Assistant Professor,
Computer EngineeringDepartment,
Sandip Institute of Polytechnic, Nashik

Email Id- rohit.kautkar@sipnashik.org


Mobile- +91-7058621533

You might also like