SlideShare a Scribd company logo
Java
Servlets
Module 4
Contents
1. The life cycle of a servlet;
2. A simple servlet;
3. the servlet API;
4. The javax.servlet package
5. Reading servlet parameter;
6. the javax.servlet.http package;
7. Handling HTTP Requests and
Responses;
8. using Cookies;
Contents
9. Session Tracking,
10. Java Server Pages (JSP); JSP tags,
Variables and Objects, Methods,
11. Control statements, Loops,
12. Request String,
13. Parsing other information,
14. User sessions,
15. Cookies, Session Objects
JavaServlets
Technology Overview
Background
How web browsers and servers cooperate to provide content to a
user?
• Consider a request for a static web page. A user enters a URL into
a browser. The browser generates an HTTP request to the
appropriate web server.
• The web server maps this request to a specific file. That file is
returned in an HTTP response to the browser. The HTTP header in
the response indicates the type of the content.
• The Multipurpose Internet Mail Extensions (MIME) are used for
this purpose.
• For example, ordinary ASCII text has a MIME type of text/plain.
The Hypertext Markup Language (HTML) source code of a web
page has a MIME type of text/html.
Background
WhatisaJavaServlets?
• A Java servlet is a server-side program that is called
by the user interface or another J2EE component and
contains the business logic to process a request.
• A Java Server Page is also a server-side program that
performs practically the same duties as a Java servlet
using a different technique.
• Both a Java servlet and a Java Server Page call other
components that handle processing details.
ServletServices
• Java Servlets provide many useful services
 Provides low-level API for building Internet services
 Serves as foundation to JavaServer Pages (JSP) and
JavaServer Faces (JSF) technologies
 Can deliver multiple types of data to any client
 XML, HTML, WML, GIF, etc...
 Can serve as “Controller” of JSP/Servlet application
WhyUseServlets?
• Portability
 Write once, serve everywhere
• Power
 Can take advantage of all Java APIs
• Elegance
 Simplicity due to abstraction
• Efficiency & Endurance
 Highly scalable
WhyUseServlets?
• Safety
 Strong type-checking
 Memory management
• Integration
 Servlets tightly coupled with server
• Extensibility & Flexibility
 Servlets designed to be easily extensible, though
currently optimized for HTTP uses
 Flexible invocation of servlet (SSI, servlet-chaining,
filters, etc.)
ASimpleServlet
• To become familiar with the key servlet concepts, we
will begin by building and testing a simple servlet.
• The basic steps are the following:
1. Create and compile the servlet source code. Then,
copy the servlet’s class file to the proper directory,
and add the servlet’s name and mappings to the
proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
TimeServlet–Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TimeServlet extends HttpServlet {
public void doGet(HttpServletRequest aRequest,
HttpServletResponse aResponse)
throws ServletException, IOException {
PrintWriter out = aResponse.getWriter();
out.println("<HTML>");
out.println("The time is: " +
new java.util.Date());
out.println("</HTML>");
}
}
Java Servlets
Technical Architecture
ServletsArchitecture
• The HttpServlet class
 Serves client's HTTP requests
• For each of the HTTP methods, GET, POST, and
others, there is corresponding method:
 doGet(…) – serves HTTP GET requests
 doPost(…) – serves HTTP POST requests
 doPut(…), doHead(…), doDelete(…), doTrace(…),
doOptions(…)
• The Servlet usually must implement one of the
first two methods or the service(…) method
ServletsArchitecture
• The HttpServletRequest object
 Contains the request data from the client
 HTTP request headers
 Form data and query parameters
 Other client data (cookies, path, etc.)
• The HttpServletResponse object
 Encapsulates data sent back to client
 HTTP response headers (content type, cookies,
etc.)
 Response body (as OutputStream)
ServletsArchitecture
• The HTTP GET method is used when:
 The processing of the request does not change the state of
the server
 The amount of form data is small
 You want to allow the request to be bookmarked
• The HTTP POST method is used when:
 The processing of the request changes the state of the
server, e.g. storing data in a DB
 The amount of form data is large
 The contents of the data should not be visible in the URL
(for example, passwords)
Java Servlets
Life Cycle
ServletsLife-Cycle
• You can provide an implementation of these methods
in HttpServlet descendent classes to manipulate the
servlet instance and the resources it depends on
• The Web container
manages the life cycle
of servlet instances
• The life-cycle methods
should not be called by
your code
init()
...()
service()
doGet()
doPost()
doDelete()
destroy()
doPut()
New Destroyed
Running
ServletsLife-Cycle
Theinit()Method
• Called by the Web container when the servlet
instance is first created
• The Servlets specification guarantees that no
requests will be processed by this servlet until the
init() method has completed
• Override the init() method when:
 You need to create or open any servlet-specific
resources that you need for processing user
requests
 You need to initialize the state of the servlet
public void init (ServletConfig config)
throws ServletException
Theservice()Method
• Called by the Web container to process a user
request
• Dispatches the HTTP requests to doGet(…),
doPost(…), etc. depending on the HTTP request
method (GET, POST, and so on)
 Sends the result as HTTP response
• Usually we do not need to override this method
public void service (ServletRequest request,
ServletResponse response) throws ServletException,IOException
Thedestroy()Method
• Called by the Web container when the servlet
instance is being eliminated
• The Servlet specification guarantees that all
requests will be completely processed before this
method is called
• Override the destroy method when:
 You need to release any servlet-specific
resources that you had opened in the init()
method
 You need to persist the state of the servlet
public void destroy()
Servlets API
The javax.servlet Package
ServletsAPI
• Two packages contain the classes and interfaces that
are required to build the servlets .
• These are javax.servlet and javax.servlet.http. They
constitute the core of the Servlet API.
• Keep in mind that these packages are not part of the
Java core packages.
• Therefore, they are not included with Java SE. Instead,
they are provided by Tomcat.
• They are also provided by Java EE.
The javax.servletPackage
• This contains a number of interfaces and classes that establish
the framework in which servlets operate
The ServletInterface
• All servlets must implement the Servlet interface.
• It declares the init( ), service( ), and destroy( ) methods that
are called by the server during the life cycle of a servlet.
• A method is also provided that allows a servlet to obtain any
initialization parameters.
• These methods are invoked by the server.
• The getServletConfig( ) method is called by the servlet to
obtain initialization parameters.
• A servlet developer overrides the getServletInfo( ) method
to provide a string with useful information (for example, the
version number). This method is also invoked by the server.
The MethodsDefinedbyServlet
The ServletConfigInterface
• The ServletConfig interface allows a servlet to obtain
configuration data when it is loaded.
• The methods declared by this interface are summarized here:
The ServletContextInterface
• The ServletContext interface enables servlets to obtain
information about their environment.
The ServletRequestInterface
• The ServletRequest interface enables a servlet to obtain
information about a client request.
The ServletRequestInterface
The ServletResponseInterface
• The ServletResponse interface enables a servlet to formulate a
response for a client.
ReadingServlet
Parameters
Examples
ProcessingParameters–Hello
Servlet
• We want to create a servlet that takes an user name
as a parameter and says "Hello, <user_name>"
• We need HTML form with a text field
• The servlet can later retrieve the value entered in the
form field
<form method="GET or POST" action="the servlet">
<input type="text" name="user_name">
</form>
String name = request.getParameter("user_name");
HelloServlet –Example
<html><body>
<form method="GET" action="HelloServlet">
Please enter your name:
<input type="text" name="user_name">
<input type="submit" value="OK">
</form>
</body></html>
HelloForm.html
HelloServlet.java
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
String userName = request.getParameter("user_name");
out.println("<html><head>");
out.println("t<title>Hello Servlet</title>");
out.println("</head><body>");
out.println("t<h1>Hello, " + userName + "</h1>");
out.println("</body></html>");
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
ParameterServlet –Example 1
<html>
<body> <center><form name="Form1" method="post"
action="http://localhost:8080/servlets-examples/
servlet/PostParametersServlet">
<table>
<tr> <td><B>Employee</td>
<td><input type=textbox name="e" size="25"
value=""></td>
</tr>
<tr> <td><B>Phone</td>
<td><input type=textbox name="p" size="25"
value=""></td>
</tr></table>
<input type=submit value="Submit">
</body>
</html>
PostParameters.html,
ParameterServlet–Example 1
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends
GenericServlet {
public void service(ServletRequest request,
ServletResponse response)throws ServletException,
IOException {
PrintWriter pw = response.getWriter();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
PostParametersServlet.java
Servlets API
The javax.servlet.http Package
The javax.servlet.httpPackage
• The classes and interfaces defined in javax.servlet, such as
ServletRequest, ServletResponse, and GenericServlet, will
illustrate the basic functionality of servlets.
• However, when working with HTTP, you will normally use the
interfaces and classes in javax.servlet.http.
ServletsAPI
• The most important servlet functionality:
 Retrieve the HTML form parameters from the
request (both GET and POST parameters)
 Retrieve a servlet initialization parameter
 Retrieve HTTP request header information
HttpServletRequest.getParameter(String)
ServletConfig.getInitParameter()
HttpServletRequest.getHeader(String)
ServletsAPI
 Set an HTTP response header / content type
 Acquire a text stream for the response
 Acquire a binary stream for the response
 Redirect an HTTP request to another URL
HttpServletResponse.setHeader(<name>,<value>)/
HttpServletResponse.setContentType(String)
HttpServletResponse.getWriter()
HttpServletResponse.getOutputStream()
HttpServletResponse.sendRedirect()
The CookieClass
• The Cookie class encapsulates a cookie. A cookie is stored
on a client and contains state information. Cookies are
valuable for tracking user activities.
• A servlet can write a cookie to a user’s machine via the
addCookie( ) method of the HttpServletResponse interface.
The data for that cookie is then included in the header of the
HTTP response that is sent to the browser.
• The names and values of cookies are stored on the user’s
machine.
1. The name of the cookie
2. The value of the cookie
3. The expiration date of the cookie
4. The domain and path of the cookie
HandlingHTTP
Requestsand
Responses
The javax.servlet.http Package
HandlingHTTPRequestsand
Responses
• The HttpServlet class provides specialized methods that
handle the various types of HTTP requests.
• A servlet developer typically overrides one of these
methods. These methods are doDelete( ), doGet( ),
doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace(
).
• However, the GET and POST requests are commonly used
when handling form input. Therefore, this section
presents examples of these cases.
HandlingHTTPGETRequests
ColorGet.html
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servle
t/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
HandlingHTTPGETRequests
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
HandlingHTTPPOSTRequests
ColorGet.html
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servle
t/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
HandlingHTTPPOSTRequests
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Using Cookies
UsingCookies
AddCookie.html
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servle
t/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
UsingCookies
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String data = request.getParameter("data");
Cookie cookie = new Cookie("MyCookie", data);
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
Session Tracking
SessionTracking
• HTTP is a stateless protocol. Each request is independent of the
previous one.
• However, in some applications, it is necessary to save state
information so that information can be collected from several
interactions between a browser and a server. Sessions provide such
a mechanism.
• A session can be created via the getSession( ) method of
HttpServletRequest.
• An HttpSession object is returned. This object can store a set of
bindings that associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames( ), and
removeAttribute( ) methods of HttpSession manage these bindings.
• Session state is shared by all servlets that are associated with a
client.
SessionTracking
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
SessionTracking
• When you call getSession() each user is automatically
assigned a unique Session ID
• How does this Session ID get to the user?
• Option 1: If the browser supports cookies, the
servlet will automatically create a session cookie,
and store the session ID within the cookie In
Tomcat, the cookie is called JSESSIONID
• Option 2: If the browser does not support cookies,
the servlet will try to extract the session ID from
the URL
Problems
1. Create a servlet that prints in a table the numbers
from 1 to 1000 and their square root.
2. Create a servlet that takes as parameters two integer
numbers and calculates their sum.
Create a HTML form that invokes the servlet. Try to
use GET and POST methods.
3. Implement a servlet that plays the "Number guess
game". When the client first invoke the servlet it
generates a random number in the range [1..100]. The
user is asked to guess this number. At each guess the
servlet says only "greater" or "smaller". The game
ends when the user tell the number.
Java Server
Pages
(JSP)
JavaServerPage(JSP)
• JSP (Java Server Pages) is server side technology to
create dynamic java web application.
• Allows Java programming code to be embedded in the
HTML pages.
• JSP contains an extension of .jsp
• After execution of a JSP page a plain HTML is
produced and displayed in the client's Web browser.
• JSP can be thought as an extension to servlet
technology because it provides features to easily
create user views.
JavaServerPageArchitecture
JavaServerPageLifeCycle
Web
Server
hello.jsp hello_jsp.java
Step: 1
Step: 2
hello_jsp.class
Step: 3
Step: 4
Step: 5
jspInit() Create
Step: 6
jspService()
Step: 7
jspDestroy()
Web
Container
JSP Life Cycle
WebContainer
• Web Container translates JSP code into a servlet class
source(.java) file, then compiles that into a java servlet
class.
• In the next step, the servlet class bytecode is loaded using
classloader. The Container then creates an instance of
that servlet class.
• The initialized servlet can now service request. For each
request the Web Container call the jspService() method.
• When the Container removes the servlet instance from
service, it calls the jspDestroy() method to perform any
required clean up.
JSPLifeCyclePhases
1. Translation – JSP pages doesn’t look like normal java
classes, actually JSP container parse the JSP pages
and translate them to generate corresponding servlet
source code. If JSP file name is hello.jsp, usually its
named as hello_jsp.java.
2. Compilation – If the translation is successful, then
container compiles the generated servlet source file to
generate class file.
3. Class Loading – Once JSP is compiled as servlet class,
its lifecycle is similar to servlet and it gets loaded into
memory.
JSPLifeCyclePhases
4. Instance Creation – After JSP class is loaded into
memory, its object is instantiated by the container.
5. Initialization – The JSP class is then initialized and it
transforms from a normal class to servlet.
6. Request Processing – For every client request, a new
thread is spawned with ServletRequest and
ServletResponse to process and generate the HTML
response.
7. Destroy – Last phase of JSP life cycle where it’s
unloaded into memory.
JSPLifecycleMethods
• Once a JSP page is translated to a servlet, the container
invokes the following life cycle methods on the servlet :
1. jspInit() : This method is invoked at the time when the
servlet is initialized.
2. jspService() : This method is invoked when request
for the JSP page is received.
3. jspDestroy() : This method is invoked before the
servlet is removes from the service.
WhathappenstoaJSPpagewhenitis
translatedintoServlet
JSPTags(Elements)
• EXPRESSION enclosed in <%= and %> markers
A expression is used to insert the result of a Java
expression directly into the output.
• SCRIPTLET enclosed in <% and %> markers:
A scriptlet can contain any number of JAVA language
statements, variable or method declarations, or
expressions that are valid in the page scripting
language.
<%
String message = “Hello World”;
out.println (message);
%>
The time is : <%= new java.util.Date() %>
JSPTags(Elements)
• DIRECTIVES syntax - <%@ directive attribute = "value" %>
A JSP directive gives special information about the JSP page to the
JSP Engine.
There are three main types of directive :-
page : processinginformation for this page
include : files to be included
taglib : tag library to be used in the page
JSPTags(Elements)
• DECLARATION enclosed in <%! and %> markers
This tag allows the developer to declare variables or
methods.
• Code placed in this must end in a semicolon(;).
• Declarations do not generate output, so are used with
JSP expressions or scriptlets.
VariablesandObjects
VariablesandObjects
Methods
Methods
ControlStatements
Loops
Loops
RequestString
• A browser generate request string whenever the submit
button is selected. The user requests the string consists of
URL and the query the string.
Example of request string:
http://www.jimkeogh.com/jsp/?fname=” Bob” & lname
=”Smith”
• Your jsp program needs to parse the query string to extract
the values of fields that are to be processed by your
program. You can parse the query string by using the
methods of the request object.
• getParameter(Name) method used to parse a value of a
specific field that are to be processed by your program
RequestString
• code to process the request string
<%! String FirstName =requst.getParameter(fname);
String LastName =requst.getParameter(lname); %>
• Copying from multivalued field such as selection list field can
be tricky multivalued fields are handled by using
getParameterValues()
• Other than request string url has protocols, port no, the host
name
• Example
<%! String [ ] EMAIL= request. getParameterValues ("EMAILADDRESS ") %>
<P><%= EMAIL [0])%> < / P>
<P><%= EMAIL [1]%> </P>
UserSession
• A JSP program must be able to track a session as a client
moves between HTML pages and JSP programs. There are
three commonly used methods to track a session.
• These are
1. by using a hidden field,
2. by using a cookie, or
3. by using a JavaBean,
HiddenField
• A hidden field is a field in an HTML form whose value isn't
displayed on the HTML page
• You can assign a value to a hidden field in a JSP program
before the program sends the dynamic HTML page to the
browser.
• A web server can send a hidden HTML form field along with
a unique session ID as follows
<input type = "hidden" name = "sessionid" value = "12345">
• Each time the web browser sends the request back, the
session_id value can be used to keep the track of different
web browsers.
Cookies-createacookie.
Cookies-Read acookie.
SessionObjects.
How to create a session attribute.
SessionObjects.
How to read session attributes.
Ad

More Related Content

Similar to Module 4.pptModule 4.pptModule 4.pptModule 4.ppt (20)

Servlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.pptServlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
MouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
kstalin2
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
KhushalChoudhary14
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
Amit Ranjan
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
pkaviya
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
sindhu991994
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
ssuser92282c
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
Eleonora Ciceri
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
joearunraja2
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
SERVIET
SERVIETSERVIET
SERVIET
sathish sak
 
Servlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.pptServlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
kstalin2
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
Amit Ranjan
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
pkaviya
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
sindhu991994
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
ssuser92282c
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
Eleonora Ciceri
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
joearunraja2
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 

More from tahirnaquash2 (7)

Academia Maven Silicon.pdfAcademia Maven Silicon.pdf
Academia Maven Silicon.pdfAcademia Maven Silicon.pdfAcademia Maven Silicon.pdfAcademia Maven Silicon.pdf
Academia Maven Silicon.pdfAcademia Maven Silicon.pdf
tahirnaquash2
 
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
tahirnaquash2
 
ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...
ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...
ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...
tahirnaquash2
 
ch10_EffiBinSearchTrees ch10_EffiBinSearchTrees
ch10_EffiBinSearchTrees ch10_EffiBinSearchTreesch10_EffiBinSearchTrees ch10_EffiBinSearchTrees
ch10_EffiBinSearchTrees ch10_EffiBinSearchTrees
tahirnaquash2
 
ch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.ppt
ch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.pptch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.ppt
ch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.ppt
tahirnaquash2
 
ch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.pptch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.ppt
tahirnaquash2
 
Intro-2013.pptIntro-2013.pptIntro-2013.ppt
Intro-2013.pptIntro-2013.pptIntro-2013.pptIntro-2013.pptIntro-2013.pptIntro-2013.ppt
Intro-2013.pptIntro-2013.pptIntro-2013.ppt
tahirnaquash2
 
Academia Maven Silicon.pdfAcademia Maven Silicon.pdf
Academia Maven Silicon.pdfAcademia Maven Silicon.pdfAcademia Maven Silicon.pdfAcademia Maven Silicon.pdf
Academia Maven Silicon.pdfAcademia Maven Silicon.pdf
tahirnaquash2
 
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
tahirnaquash2
 
ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...
ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...
ATAL_Online_6_Days_Faculty_Development_Programme_Selected_List_for_A.Y_2024-2...
tahirnaquash2
 
ch10_EffiBinSearchTrees ch10_EffiBinSearchTrees
ch10_EffiBinSearchTrees ch10_EffiBinSearchTreesch10_EffiBinSearchTrees ch10_EffiBinSearchTrees
ch10_EffiBinSearchTrees ch10_EffiBinSearchTrees
tahirnaquash2
 
ch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.ppt
ch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.pptch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.ppt
ch10_Key_Management.ppt ch10_Key_Management.ppt ch10_Key_Management.ppt
tahirnaquash2
 
ch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.pptch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.ppt
tahirnaquash2
 
Intro-2013.pptIntro-2013.pptIntro-2013.ppt
Intro-2013.pptIntro-2013.pptIntro-2013.pptIntro-2013.pptIntro-2013.pptIntro-2013.ppt
Intro-2013.pptIntro-2013.pptIntro-2013.ppt
tahirnaquash2
 
Ad

Recently uploaded (20)

Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Ad

Module 4.pptModule 4.pptModule 4.pptModule 4.ppt

  • 2. Contents 1. The life cycle of a servlet; 2. A simple servlet; 3. the servlet API; 4. The javax.servlet package 5. Reading servlet parameter; 6. the javax.servlet.http package; 7. Handling HTTP Requests and Responses; 8. using Cookies;
  • 3. Contents 9. Session Tracking, 10. Java Server Pages (JSP); JSP tags, Variables and Objects, Methods, 11. Control statements, Loops, 12. Request String, 13. Parsing other information, 14. User sessions, 15. Cookies, Session Objects
  • 5. Background How web browsers and servers cooperate to provide content to a user? • Consider a request for a static web page. A user enters a URL into a browser. The browser generates an HTTP request to the appropriate web server. • The web server maps this request to a specific file. That file is returned in an HTTP response to the browser. The HTTP header in the response indicates the type of the content. • The Multipurpose Internet Mail Extensions (MIME) are used for this purpose. • For example, ordinary ASCII text has a MIME type of text/plain. The Hypertext Markup Language (HTML) source code of a web page has a MIME type of text/html.
  • 7. WhatisaJavaServlets? • A Java servlet is a server-side program that is called by the user interface or another J2EE component and contains the business logic to process a request. • A Java Server Page is also a server-side program that performs practically the same duties as a Java servlet using a different technique. • Both a Java servlet and a Java Server Page call other components that handle processing details.
  • 8. ServletServices • Java Servlets provide many useful services  Provides low-level API for building Internet services  Serves as foundation to JavaServer Pages (JSP) and JavaServer Faces (JSF) technologies  Can deliver multiple types of data to any client  XML, HTML, WML, GIF, etc...  Can serve as “Controller” of JSP/Servlet application
  • 9. WhyUseServlets? • Portability  Write once, serve everywhere • Power  Can take advantage of all Java APIs • Elegance  Simplicity due to abstraction • Efficiency & Endurance  Highly scalable
  • 10. WhyUseServlets? • Safety  Strong type-checking  Memory management • Integration  Servlets tightly coupled with server • Extensibility & Flexibility  Servlets designed to be easily extensible, though currently optimized for HTTP uses  Flexible invocation of servlet (SSI, servlet-chaining, filters, etc.)
  • 11. ASimpleServlet • To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. • The basic steps are the following: 1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and add the servlet’s name and mappings to the proper web.xml file. 2. Start Tomcat. 3. Start a web browser and request the servlet.
  • 12. TimeServlet–Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimeServlet extends HttpServlet { public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException { PrintWriter out = aResponse.getWriter(); out.println("<HTML>"); out.println("The time is: " + new java.util.Date()); out.println("</HTML>"); } }
  • 14. ServletsArchitecture • The HttpServlet class  Serves client's HTTP requests • For each of the HTTP methods, GET, POST, and others, there is corresponding method:  doGet(…) – serves HTTP GET requests  doPost(…) – serves HTTP POST requests  doPut(…), doHead(…), doDelete(…), doTrace(…), doOptions(…) • The Servlet usually must implement one of the first two methods or the service(…) method
  • 15. ServletsArchitecture • The HttpServletRequest object  Contains the request data from the client  HTTP request headers  Form data and query parameters  Other client data (cookies, path, etc.) • The HttpServletResponse object  Encapsulates data sent back to client  HTTP response headers (content type, cookies, etc.)  Response body (as OutputStream)
  • 16. ServletsArchitecture • The HTTP GET method is used when:  The processing of the request does not change the state of the server  The amount of form data is small  You want to allow the request to be bookmarked • The HTTP POST method is used when:  The processing of the request changes the state of the server, e.g. storing data in a DB  The amount of form data is large  The contents of the data should not be visible in the URL (for example, passwords)
  • 18. ServletsLife-Cycle • You can provide an implementation of these methods in HttpServlet descendent classes to manipulate the servlet instance and the resources it depends on • The Web container manages the life cycle of servlet instances • The life-cycle methods should not be called by your code init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running
  • 20. Theinit()Method • Called by the Web container when the servlet instance is first created • The Servlets specification guarantees that no requests will be processed by this servlet until the init() method has completed • Override the init() method when:  You need to create or open any servlet-specific resources that you need for processing user requests  You need to initialize the state of the servlet public void init (ServletConfig config) throws ServletException
  • 21. Theservice()Method • Called by the Web container to process a user request • Dispatches the HTTP requests to doGet(…), doPost(…), etc. depending on the HTTP request method (GET, POST, and so on)  Sends the result as HTTP response • Usually we do not need to override this method public void service (ServletRequest request, ServletResponse response) throws ServletException,IOException
  • 22. Thedestroy()Method • Called by the Web container when the servlet instance is being eliminated • The Servlet specification guarantees that all requests will be completely processed before this method is called • Override the destroy method when:  You need to release any servlet-specific resources that you had opened in the init() method  You need to persist the state of the servlet public void destroy()
  • 24. ServletsAPI • Two packages contain the classes and interfaces that are required to build the servlets . • These are javax.servlet and javax.servlet.http. They constitute the core of the Servlet API. • Keep in mind that these packages are not part of the Java core packages. • Therefore, they are not included with Java SE. Instead, they are provided by Tomcat. • They are also provided by Java EE.
  • 25. The javax.servletPackage • This contains a number of interfaces and classes that establish the framework in which servlets operate
  • 26. The ServletInterface • All servlets must implement the Servlet interface. • It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. • A method is also provided that allows a servlet to obtain any initialization parameters. • These methods are invoked by the server. • The getServletConfig( ) method is called by the servlet to obtain initialization parameters. • A servlet developer overrides the getServletInfo( ) method to provide a string with useful information (for example, the version number). This method is also invoked by the server.
  • 28. The ServletConfigInterface • The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. • The methods declared by this interface are summarized here:
  • 29. The ServletContextInterface • The ServletContext interface enables servlets to obtain information about their environment.
  • 30. The ServletRequestInterface • The ServletRequest interface enables a servlet to obtain information about a client request.
  • 32. The ServletResponseInterface • The ServletResponse interface enables a servlet to formulate a response for a client.
  • 34. ProcessingParameters–Hello Servlet • We want to create a servlet that takes an user name as a parameter and says "Hello, <user_name>" • We need HTML form with a text field • The servlet can later retrieve the value entered in the form field <form method="GET or POST" action="the servlet"> <input type="text" name="user_name"> </form> String name = request.getParameter("user_name");
  • 35. HelloServlet –Example <html><body> <form method="GET" action="HelloServlet"> Please enter your name: <input type="text" name="user_name"> <input type="submit" value="OK"> </form> </body></html> HelloForm.html
  • 36. HelloServlet.java public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); String userName = request.getParameter("user_name"); out.println("<html><head>"); out.println("t<title>Hello Servlet</title>"); out.println("</head><body>"); out.println("t<h1>Hello, " + userName + "</h1>"); out.println("</body></html>"); } import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet {
  • 37. ParameterServlet –Example 1 <html> <body> <center><form name="Form1" method="post" action="http://localhost:8080/servlets-examples/ servlet/PostParametersServlet"> <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr></table> <input type=submit value="Submit"> </body> </html> PostParameters.html,
  • 38. ParameterServlet–Example 1 import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException { PrintWriter pw = response.getWriter(); Enumeration e = request.getParameterNames(); while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } } PostParametersServlet.java
  • 40. The javax.servlet.httpPackage • The classes and interfaces defined in javax.servlet, such as ServletRequest, ServletResponse, and GenericServlet, will illustrate the basic functionality of servlets. • However, when working with HTTP, you will normally use the interfaces and classes in javax.servlet.http.
  • 41. ServletsAPI • The most important servlet functionality:  Retrieve the HTML form parameters from the request (both GET and POST parameters)  Retrieve a servlet initialization parameter  Retrieve HTTP request header information HttpServletRequest.getParameter(String) ServletConfig.getInitParameter() HttpServletRequest.getHeader(String)
  • 42. ServletsAPI  Set an HTTP response header / content type  Acquire a text stream for the response  Acquire a binary stream for the response  Redirect an HTTP request to another URL HttpServletResponse.setHeader(<name>,<value>)/ HttpServletResponse.setContentType(String) HttpServletResponse.getWriter() HttpServletResponse.getOutputStream() HttpServletResponse.sendRedirect()
  • 43. The CookieClass • The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. • A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser. • The names and values of cookies are stored on the user’s machine. 1. The name of the cookie 2. The value of the cookie 3. The expiration date of the cookie 4. The domain and path of the cookie
  • 45. HandlingHTTPRequestsand Responses • The HttpServlet class provides specialized methods that handle the various types of HTTP requests. • A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). • However, the GET and POST requests are commonly used when handling form input. Therefore, this section presents examples of these cases.
  • 46. HandlingHTTPGETRequests ColorGet.html <html> <body> <center> <form name="Form1" action="http://localhost:8080/examples/servlets/servle t/ColorGetServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html>
  • 47. HandlingHTTPGETRequests ColorGetServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } }
  • 48. HandlingHTTPPOSTRequests ColorGet.html <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servle t/ColorPostServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html>
  • 49. HandlingHTTPPOSTRequests ColorGetServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorPostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } }
  • 51. UsingCookies AddCookie.html <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servle t/AddCookieServlet"> <B>Enter a value for MyCookie:</B> <input type=textbox name="data" size=25 value=""> <input type=submit value="Submit"> </form> </body> </html>
  • 52. UsingCookies AddCookieServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = request.getParameter("data"); Cookie cookie = new Cookie("MyCookie", data); response.addCookie(cookie); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close(); } }
  • 54. SessionTracking • HTTP is a stateless protocol. Each request is independent of the previous one. • However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. • A session can be created via the getSession( ) method of HttpServletRequest. • An HttpSession object is returned. This object can store a set of bindings that associate names with objects. • The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings. • Session state is shared by all servlets that are associated with a client.
  • 55. SessionTracking public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the HttpSession object. HttpSession hs = request.getSession(true); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>"); Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } }
  • 56. SessionTracking • When you call getSession() each user is automatically assigned a unique Session ID • How does this Session ID get to the user? • Option 1: If the browser supports cookies, the servlet will automatically create a session cookie, and store the session ID within the cookie In Tomcat, the cookie is called JSESSIONID • Option 2: If the browser does not support cookies, the servlet will try to extract the session ID from the URL
  • 57. Problems 1. Create a servlet that prints in a table the numbers from 1 to 1000 and their square root. 2. Create a servlet that takes as parameters two integer numbers and calculates their sum. Create a HTML form that invokes the servlet. Try to use GET and POST methods. 3. Implement a servlet that plays the "Number guess game". When the client first invoke the servlet it generates a random number in the range [1..100]. The user is asked to guess this number. At each guess the servlet says only "greater" or "smaller". The game ends when the user tell the number.
  • 59. JavaServerPage(JSP) • JSP (Java Server Pages) is server side technology to create dynamic java web application. • Allows Java programming code to be embedded in the HTML pages. • JSP contains an extension of .jsp • After execution of a JSP page a plain HTML is produced and displayed in the client's Web browser. • JSP can be thought as an extension to servlet technology because it provides features to easily create user views.
  • 61. JavaServerPageLifeCycle Web Server hello.jsp hello_jsp.java Step: 1 Step: 2 hello_jsp.class Step: 3 Step: 4 Step: 5 jspInit() Create Step: 6 jspService() Step: 7 jspDestroy() Web Container JSP Life Cycle
  • 62. WebContainer • Web Container translates JSP code into a servlet class source(.java) file, then compiles that into a java servlet class. • In the next step, the servlet class bytecode is loaded using classloader. The Container then creates an instance of that servlet class. • The initialized servlet can now service request. For each request the Web Container call the jspService() method. • When the Container removes the servlet instance from service, it calls the jspDestroy() method to perform any required clean up.
  • 63. JSPLifeCyclePhases 1. Translation – JSP pages doesn’t look like normal java classes, actually JSP container parse the JSP pages and translate them to generate corresponding servlet source code. If JSP file name is hello.jsp, usually its named as hello_jsp.java. 2. Compilation – If the translation is successful, then container compiles the generated servlet source file to generate class file. 3. Class Loading – Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it gets loaded into memory.
  • 64. JSPLifeCyclePhases 4. Instance Creation – After JSP class is loaded into memory, its object is instantiated by the container. 5. Initialization – The JSP class is then initialized and it transforms from a normal class to servlet. 6. Request Processing – For every client request, a new thread is spawned with ServletRequest and ServletResponse to process and generate the HTML response. 7. Destroy – Last phase of JSP life cycle where it’s unloaded into memory.
  • 65. JSPLifecycleMethods • Once a JSP page is translated to a servlet, the container invokes the following life cycle methods on the servlet : 1. jspInit() : This method is invoked at the time when the servlet is initialized. 2. jspService() : This method is invoked when request for the JSP page is received. 3. jspDestroy() : This method is invoked before the servlet is removes from the service.
  • 67. JSPTags(Elements) • EXPRESSION enclosed in <%= and %> markers A expression is used to insert the result of a Java expression directly into the output. • SCRIPTLET enclosed in <% and %> markers: A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. <% String message = “Hello World”; out.println (message); %> The time is : <%= new java.util.Date() %>
  • 68. JSPTags(Elements) • DIRECTIVES syntax - <%@ directive attribute = "value" %> A JSP directive gives special information about the JSP page to the JSP Engine. There are three main types of directive :- page : processinginformation for this page include : files to be included taglib : tag library to be used in the page
  • 69. JSPTags(Elements) • DECLARATION enclosed in <%! and %> markers This tag allows the developer to declare variables or methods. • Code placed in this must end in a semicolon(;). • Declarations do not generate output, so are used with JSP expressions or scriptlets.
  • 75. Loops
  • 76. Loops
  • 77. RequestString • A browser generate request string whenever the submit button is selected. The user requests the string consists of URL and the query the string. Example of request string: http://www.jimkeogh.com/jsp/?fname=” Bob” & lname =”Smith” • Your jsp program needs to parse the query string to extract the values of fields that are to be processed by your program. You can parse the query string by using the methods of the request object. • getParameter(Name) method used to parse a value of a specific field that are to be processed by your program
  • 78. RequestString • code to process the request string <%! String FirstName =requst.getParameter(fname); String LastName =requst.getParameter(lname); %> • Copying from multivalued field such as selection list field can be tricky multivalued fields are handled by using getParameterValues() • Other than request string url has protocols, port no, the host name • Example <%! String [ ] EMAIL= request. getParameterValues ("EMAILADDRESS ") %> <P><%= EMAIL [0])%> < / P> <P><%= EMAIL [1]%> </P>
  • 79. UserSession • A JSP program must be able to track a session as a client moves between HTML pages and JSP programs. There are three commonly used methods to track a session. • These are 1. by using a hidden field, 2. by using a cookie, or 3. by using a JavaBean,
  • 80. HiddenField • A hidden field is a field in an HTML form whose value isn't displayed on the HTML page • You can assign a value to a hidden field in a JSP program before the program sends the dynamic HTML page to the browser. • A web server can send a hidden HTML form field along with a unique session ID as follows <input type = "hidden" name = "sessionid" value = "12345"> • Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers.
  • 83. SessionObjects. How to create a session attribute.
  • 84. SessionObjects. How to read session attributes.

Editor's Notes