Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Java New Servlets

Java servlets are used to create dynamic web pages and handle HTTP requests and responses. Servlets act as a middle layer between requests from clients and databases or applications on the server. Servlets have advantages over CGI like being platform independent and supporting security managers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Java New Servlets

Java servlets are used to create dynamic web pages and handle HTTP requests and responses. Servlets act as a middle layer between requests from clients and databases or applications on the server. Servlets have advantages over CGI like being platform independent and supporting security managers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

SERVLETS

Introduction
 Need for creating Dynamic Web Pages.
 Java Servlets are used to design dynamic web
pages.
 Servlets are the Java programs that runs on the

Java-enabled web server or application server.


 They are used to handle the request obtained
from the web server, process the request,
produce the response, then send response back
to the web server.
Introduction
 Java Servlets act
as a middle layer
between a request
coming from a
Web browser or
other HTTP client
and databases or
applications on the
HTTP server.
Common Gateway Interface
 In client- server computing, each application had
its own client program and it worked as a user
interface.
 It was supposed to be installed on each user's
personal computer.
 The Common Gateway Interface (CGI) was
developed for creating dynamic content.
 By using the CGI, a web server passes requests to
an external program and after executing the
program the content is sent to the client as the
output.
Common Gateway Interface
 CGI creates a new process when a server
receives a request.
 CGI creates a process for each request.

 This required significant server resources and

time.
 Limited number of requests that can be
processed concurrently.
 CGI applications are platform dependent.
Servlets
 Java Servlets are programs that run on a Web
or Application server and act as a middle layer
between a request coming from a Web
browser or other HTTP client and databases or
applications on the HTTP server.
Servlets
 Using Servlets, you can collect input from
users through web page forms, present records
from a database or another source, and create
web pages dynamically.

 Java Servlets often serve the same purpose as


Common Gateway Interface (CGI) but offer
several advantages.
Servlets vs CGI
SERVLETS CGI
Platform Independent Platform Dependent
Every request is handled by a Every request is handled by a
lightweight Java Thread. heavyweight Process.
Java security manager on the server No support for Security Manager
protects the resources on a server
machine.
Availability of complete Java class Limited Libraries
libraries
Servlets can share data among each other CGI does not provide sharing property

Servlets can perform session tracking CGI cannot perform session tracking
Servlets can read and set HTTP headers, CGI can’t read and set HTTP headers,
handle cookies handle cookies
Servlet Applications
 Search engines
 E-commerce applications

 Shopping carts

 Product catalogs

 Intranet application

 Groupware applications: bulletin boards, file


sharing, etc.
Servlet Life Cycle

1. Load Servlet Class.


2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.
Servlet Life Cycle
 Browser sends a HTTP request to the web server
(through URL, submitting a form, etc)

 Web server receives the request and maps this request


to a particular Servlet.
 The servlet is retrieved and dynamically loaded into the server
address space.

 init() method of the servlet is called by the web server


only when the servlet is first loaded into the memory.
public void init() throws ServletException {
// Initialization code...
}
Servlet Life Cycle
 Web server invokes service() method of the servlet.
 This method is called to process the HTTP request.
 Read the parameters from the request and send a response
back to the browser.
 The servlet remains in the server’s address space and is
available to process any other HTTP requests received from
clients.
 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.
Servlet Life Cycle
 Signature of service()
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{ }

 The server decides to unload the servlet from its


memory and calls the destroy() method to relinquish
any resources.
public void destroy() {
// Finalization code...
}
Servlet Life Cycle
 When HTTP calls for a
Servlet
 Not loaded: Load, Create,
Init, Service
 Already loaded: Service
Servlet Life Cycle
Servlet Container
 Servlet container is the component of a web server that
interacts with Java servlets.
 A Servlet container is responsible for
 Managing the lifecycle of servlets.
 Mapping a URL to a particular servlet
 Ensuring that the URL requester has the correct access rights.
 A web container implements the web component contract
of the Java EE architecture, specifying a runtime
environment for web components that includes security,
concurrency, lifecycle management, transaction,
deployment, and other services.
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)
throws ServletException, IOException {
// Servlet code
}
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)
throws ServletException, IOException {
// Servlet code
}
Generic Servlet vs HTTP servlet
 There are two different kinds of servlet classes.

1. GenericServlet is just that, a generic, protocol-independent


servlet.

2. HttpServlet is a servlet tied specifically to the HTTP


protocol.
Generic Servlet vs HTTP servlet

GenericServlet HttpServlet
Defines a generic, protocol- Defines a HTTP protocol specific
independent servlet. servlet.

Gives a blueprint and makes writing Gives a blueprint for Http servlet and
servlet easier. makes writing them easier.

provides simple versions of the


extends the GenericServlet and hence
lifecycle methods init, service, and
inherits the properties of
destroy and of the methods in the
GenericServlet.
ServletConfig interface
Servlet Libraries
 Two packages contain the classes and interfaces that
are required to build servlets. These are
1. javax.servlet, and
2. javax.servlet.http.

 They constitute the Servlet API.


 These packages are not part of the Java core
packages.
 Instead, they are standard extensions provided by the
web servers.
javax.servlet package

Interfaces Description

Servlet Declares life cycle methods for a Servlet

ServletConfig Allows Servlets to get initialization parameters

Enables servlets to log events and access


ServletContext information about their
environment.

ServletRequest Used to read data from a client request

ServletResponse Used to write data to a client response


javax.servlet package

Classes Description

Implements the Servlet and


GenericServlet
ServletConfig interfaces.
Provides an input stream for reading
ServletInputStream
requests from a client
Provides an output stream for writing
ServletOutputStream responses to a client

ServletException Indicates a Servlet error occurred.

UnavailableException Indicates a Servlet is unavailable.


javax.servlet.http package

Interfaces Description

Enables servlets to read data from


HttpServletRequest
an HTTP request

Enables servlets to write data to an


HttpServletResponse
HTTP response

Allows session data to be read and


HttpSession
written

Informs an object that it is bound


HttpSessionBindingListener
to or unbound from a session
javax.servlet.http package

Classes Description

Allows state information to be stored


Cookie
on a client machine
Provides methods to handle HTTP
HttpServlet
requests and responses

HttpSessionEvent Encapsulates a session-changed event

Indicates when a listener is bound to or


HttpSessionBindingEvent unbound from a session value, or that a
session attribute changed
Servlet Example
 HelloServlet Example:

1. HelloServlet.java : A servlet, which is a Java class


file
2. hello.html : A web page to invoke the servlet by
sending a request
3. web.xml : A deployment descriptor which will map
the request from the web page to the servlet
Servlet Example
Servlet Example : HelloServlet.java
Servlet Example : hello.html
Servlet Example : web.xml
Servlet Example : Run hello.html on
the server
Servlet Example : Run hello.html on
the server
HTML Markup from Servlet
Form Data
 Basics of HTML forms
 Use the FORM element to create an HTML form
 ACTION attribute to designate the address of the servlet or
JSP page that will process the results.
 <FORM ACTION="...">...</FORM>

 If ACTION is omitted, the data is submitted to the URL of


the current page.
 Use input elements to collect user data.
 Place the elements between the start and end tags of the
FORM element and give each input element a NAME.
 <INPUT TYPE="TEXT" NAME="...">
Form Data
 Place a submit button near the bottom of the form.
 <INPUT TYPE="SUBMIT">
 When the button is pressed, the URL designated by the
form’s ACTION is invoked.
 With GET requests, a question mark and name/value pairs
are attached to the end of the URL, where the names come
from the NAME attributes in the HTML input elements and
the values come from the end user.
 With POST requests, the same data is sent, but on a
separate request line instead of attached to the URL.
Reading Form Data from Servlets
 getParameter ()
 Reading Single Values
 To read a request (form) parameter, you simply call the
getParameter method of HttpServletRequest, supplying
the case-sensitive parameter name as an argument.
 Supply the parameter name exactly as it appeared in
the HTML source code.
 The servlet knows which request method the client
used and automatically uses the appropriate method to
read the data.
Reading Form Data from Servlets
 getParameter ()
 Returns Empty String if the parameter exists but has
no value (i.e., the user left the corresponding textfield
empty when submitting the form).
 Returns Null if there is no such parameter.

 Returns String which corresponds to the parameter.

 Parameter names are case sensitive so,


request.getParameter("Param1") and
request.getParameter("param1") are not
interchangeable.
Reading Form Data from Servlets
 getParameter ()
 Named Field values HTML FORM

<INPUT TYPE="TEXT" NAME=“FName">

 In Servlet

String name = request.getParameter(“FName");


Reading Form Data from Servlets
 getParameterValues()
 Ifthe same parameter name might appear in the form
data more than once, you should call
getParameterValues (which returns an array of strings)
instead of getParameter.
 The return value of getParameterValues is null for
nonexistent parameter names and is a one-element
array when the parameter has only a single value.
 Best to ensure that each textfield, checkbox, or other
user interface element has a unique name.
Reading Form Data from Servlets
 getParameterNames()
 Use getParameterNames to get the full list of
parameter names in the form of an Enumeration.
 Each entry of this Enumeration can be cast to a String
and used in a getParameter or getParameterValues call.
 If there are no parameters in the current request,
getParameterNames returns an empty Enumeration
(not null).
Reading Form Data from Servlets
 getParameterMap()
 An alternative to getParameterNames is
getParameterMap.
 This method returns a Map: the parameter names
(strings) are the table keys and the parameter values
are the table values.
 Parameter Values are the string arrays as returned by
getParameterNames.
Reading request parameters
 Example
 ReadParamServlet.java : A servlet, which is a Java
class file. It reads the parameters from the request.
 passParam.html : A web page to invoke the servlet by
sending a request. It passes the parameters to the
servlet.
 web.xml : A deployment descriptor which will map the
request from the web page to the servlet Parameter
Values are the string arrays as returned by
getParameterNames.
Reading request parameters
Reading request parameters
Reading request parameters
Reading request parameters
Reading request parameters
Reading request parameters
HttpServlet
 Whenever the web browser fetches a file (a page, a
picture, etc) from a web server, it does so using
HTTP (Hypertext Transfer Protocol).
 HTTP is a request/response protocol, which means
your computer sends a request for some file, and the
web server sends back a response.
 HTTP 1.1 defines the following request methods:
 GET: Retrieves the resource identified by the request
URL
 HEAD: Returns the headers identified by the request
URL
HttpServlet
 POST: Sends data of unlimited length to the Web
server
 PUT: Stores a resource under the request URL
 DELETE: Removes the resource identified by the
request URL
 OPTIONS: Returns the HTTP methods the server
supports
 TRACE: Returns the header fields sent with the
TRACE request
HTTP Get request
 Example
 GetRequestServlet.java: An HTTP servlet, which is
a Java class that extends HttpServlet.
 getRequest.html: A web page to invoke the servlet
by sending a request. It sends a GET request.
 web.xml: A deployment descriptor which will map
the request from the web page to the servlet.
HTTP Get request
HTTP Get request
HTTP Get request
HTTP Get request
HTTP Get request
HTTP Get request
HTTP Post request
 Example
 PostRequestServlet.java: An HTTP servlet, which
is a Java class that extends HttpServlet.
 postRequest.html: A web page to invoke the servlet
by sending a request. It sends a POST request.
 web.xml: A deployment descriptor which will map
the request from the web page to the servlet.
HTTP Post request
HTTP Post request
HTTP Post request
HTTP Post request
HTTP Post request
HTTP Get vs HTTP Post
HTTP Get Request HTTP Post Request
Get Request sends the request parameter Post request send the request parameters
as query string appended at the end of as part of the http request body.
the request.
Example: Example:
http://localhost:8080/PractiseApp/getReq http://localhost:8080/PractiseApp/postRe
? username=Ashok&password=lordshiva q
Restriction on form data, only ASCII No Restriction on form data, Binary data
characters allowed. is also allowed.
Get methods have maximum size as Post methods have maximum size is 8
2000 character. mb.
Restriction on form length, So URL No restriction on form data.
length is restricted
Remain in browser history. Never remain the browser history.
Cookies
 Web applications are typically a series of HTTP
requests and responses.
 As HTTP is a stateless protocol, information is not
automatically saved between HTTP requests.
 Web applications use cookies to store state
information on the client.
 Cookies can be used to store information about the
user, the user's shopping cart, and so on.
 Cookies are small bits of textual information that a
Web server sends to a browser.
Cookies
 By having the server read cookies it sent the client
previously, the site can provide visitors with a
number of conveniences like
 Identifyinga user during e-commerce session
 Avoiding username and password entered again and
again
 Customizing a site based on user's browsing history

 Focusing Advertisement
Cookies
 The Cookie class provides an easy way for servlet to
read, create, and manipulate HTTP cookies on the
web browser.
 getCookies():To retrieve cookies as request.
 addCookie(): To send a new cookie to the browser.

 setMaxAge(): To set the age of cookie.


Cookies
 Creating a cookie and store in browser
 Cookie ck=new Cookie("key", "value");

 To add cookie expiry time


 ck.serMaxAge(300); // seconds ie 5 min

 To add Cookie to HTTP response header.


 response.addCookie(ck);
Cookies
 To retrieve Cookie from browser
 Cookie cks[]=request.getCookies();

 To remove a Cookie, just set the value as null and age


as 0.
 Cookie ck=new Cookie("key",null);
 ck.setMaxAge(0);

 response.addCookie(ck);
Creating a Cookie
 Example
 WriteCookie.java : An HTTP servlet, which is a
Java class that extends HttpServlet.
 cookieWrite.html : A web page to invoke the servlet
by sending a request.
 web.xml : A deployment descriptor which will map
the request from the web page to the servlet.
Creating a Cookie
Creating a Cookie
Creating a Cookie
Creating a Cookie
Creating a Cookie
Reading a Cookie
 Example
 ReadCookieServlet.java : An HTTP servlet, which
is a Java class that extends HttpServlet.
 cookieRead.html : A web page to invoke the servlet
by sending a request.
 web.xml : A deployment descriptor which will map
the request from the web page to the servlet.
Reading a Cookie
Reading a Cookie
Reading a Cookie
Reading a Cookie
Reading a Cookie
Session Handling
 HTTP is a “stateless” protocol.
 Each time a client retrieves a Web page, the client opens
a separate connection to the Web server and the server
does not automatically maintain contextual information
about the client.
 No built-in support for maintaining contextual
information in Server.
 There are 4 typical solutions to this problem:
 Cookies
 URL rewriting

 Hidden form fields

 HttpSession
Session Handling
 Cookies:
 A web server can assign a unique session ID as a
cookie to each web client and for subsequent requests
from the client they can be recognized using the
received cookie.
 URL rewriting:
 You can append some extra data on the end of each
URL that identifies the session, and the server can
associate that session identifier with data it has stored
about that session.
 http://jmaster.in/home.html;sessionid=12345
Session Handling
 Hidden form fields:
 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">
 This entry means that, when the form is submitted, the
specified name and value are automatically included in
the request.
 Each time when web browser sends request back, then
session_id value can be used to keep the track of
different web browsers.
Session Handling
 HttpSession:
 Servlet provides HttpSession Interface which 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.
 The servlet container uses this interface to create a
session between an HTTP client and an HTTP server.
 The session persists for a specified time period, across
more than one connection or page request from the
user.
Session Tracking Basics
 Using sessions in servlets is straightforward and
involves four basic steps.
 Accessing the session object associated with the
current request
 Call request.getSession() to get an HttpSession object,
which is a simple hash table for storing user-specific
data.
 Looking up information associated with a session
 Call getAttribute() on the HttpSession object, cast the
return value to the appropriate type, and check whether
the result is null.
Session Tracking Basics
 Storing information in a session
 Use setAttribute() with a key and a value.

 Discarding session data


 Call removeAttribute() to discard a specific value. Call
invalidate() to discard an entire session.
 Call logout() to log the client out of the Web server and
invalidate all session associated with that user.
Session Handling
 Example
 SessionTrackServlet.java : An HTTP servlet, which
is a Java class that extends HttpServlet.
 sessionTrack.html : A web page to invoke the
servlet by sending a request.
 web.xml : A deployment descriptor which will map
the request from the web page to the servlet.
Session Handling
Session Handling
Session Handling
Session Handling
Session Handling
Servlet Collaboration
 The exchange of information among servlets of a
particular Java web application is known as Servlet
Collaboration.
 This enables passing/sharing information from one
servlet to the other through method invocations.

 The servlet api provides two interfaces namely:


 javax.servlet.RequestDispatcher

 javax.servlet.http.HttpServletResponse
RequestDispatcher in Servlet
 The RequestDispatcher interface provides the facility
of dispatching the request to another resource it may
be html, servlet or jsp.
 This interface can also be used to include the content
of another resource also. It is one of the way of
servlet collaboration.
 There are two methods defined in the
RequestDispatcher interface.
 forward()

 include()
RequestDispatcher in Servlet
 public void forward (ServletRequest
request,ServletResponse response)throws
ServletException,java.io.IOException:
 Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.

 public void include (ServletRequest


request,ServletResponse response)throws
ServletException,java.io.IOException:
 Includes the content of a resource (servlet, JSP page,
or HTML file) in the response.
forward() in RequestDispatcher
include() in RequestDispatcher
Example on RequestDispatcher
Example on RequestDispatcher
Example on RequestDispatcher
Example on RequestDispatcher
Example on RequestDispatcher
sendRedirect() of HttpServletResponse

 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.

 It can work inside and outside the server.


forward() vs sendRedirect()
forward() sendRedirect()
The forward() method works at The sendRedirect() method
server side. works 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 It can be used within and
only. outside the server.
request.getRequestDispacher response.sendRedirect
("servlet2").forward(request, ("servlet2");
response);
Example on sendRedirect()
Example on sendRedirect()
Example on sendRedirect()
THANK YOU

You might also like