0% found this document useful (0 votes)
11 views

Java Servlet

Uploaded by

Afeena Syed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Servlet

Uploaded by

Afeena Syed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Java

Servlet
What is a Servlet?
• Servlet is a technology i.e. used to create web application.
• Servlet is an API that provides many interfaces and classes
including documentations.
• Servlet is an interface that must be implemented for creating any
servlet.
• Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any type of
requests.
• Servlet is a web component that is deployed on the server to create
dynamic web page.
Server-side Programming
• The combination of
• HTML
• JavaScript
• DOM
is sometimes referred to as Dynamic HTML
(DHTML)
• Web pages that include scripting are often
called dynamic pages (vs. static)
Server-side Programming
• Similarly, web server response can be static or
dynamic
• Static: HTML document is retrieved from the file system
and returned to the client
• Dynamic: HTML document is generated by a program in
response to an HTTP request
• Java servlets are one technology for producing
dynamic server responses
• Servlet is a class instantiated by the server to produce a
dynamic response
CGI(Commmon Gateway Interface)

• CGI technology enables the web server to call an


external program and pass HTTP request information
to the external program to process the request.

• For each request, it starts a new process.


Disadvantages of CGI

There are many problems in CGI technology:

• If number of clients increases, it takes more time for


sending response.
• For each request, it starts a process and Web server is
limited to start processes.
• It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet

• The web container creates threads for handling the


multiple requests to the servlet.

• Threads have a lot of benefits over the Processes


such as they share a common memory area,
lightweight, cost of communication between the
threads are low.
The basic benefits of servlet are as follows:
• Better performance: because it creates a thread for each
request not process.

• Portability: because it uses java language.

• Robust: Servlets are managed by JVM so we don't need to


worry about memory leak, garbage collection etc.

• Secure: because it uses java language


Benefits of servlet
• Portability
• Powerful
• Efficiency
• Safety
• Integration
• Extensibility
• Inexpensive
• Secure
• Performance
Lifecycle

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
Simple Servlet
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
The Servlet API
Building Servlets require javax.servlet and javax.servlet.http.
• The javax.servlet package
interfaces and classes not specific to any protocol.
• The javax.servlet.http package
interfaces and classes that are responsible for http requests only.
The javax.servlet Package
The Servlet Interface
The ServletConfig Interface
The ServletRequest Interface
The ServletResponse Interface
Reading Servlet Parameters
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/ReadingParameters/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>
Reading Servlet Parameters…
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
} }
The javax.servlet.http Package
The
HttpServlet
Request
Interface
The
HttpServlet
Response
Interface
The Cookie Class
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
Some of the information that is saved for each cookie includes the
following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
The Cookie Class…
Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods that handle the
various types of HTTP requests..
These methods are
doDelete( ),
doGet( ),
doHead( ),
doOptions( ),
doPost( ),
doPut( ), and doTrace( ).
GET and POST requests are commonly used when handling form input
Get vs. Post
GET POST

1) In case of Get request, only limited amount In case of post request, large amount of
of data can be sent because data is sent in data can be sent because data is sent in
header. body.
2) Get request is not secured because data is Post request is secured because data is
exposed in URL bar. not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent. It means second Post request is non-idempotent.
request will be ignored until response of first
request is delivered
5) Get request is more efficient and used more Post request is less efficient and used
than Post. less than get.
Session Tracking
• HTTP is a stateless protocol.
• Sessions provide storage of session information.
• 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.
• It is important to note that session state is shared among all the
servlets that are associated with a particular client.
• import java.io.*;
• import java.util.*;
• import javax.servlet.*;

Session •

import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
Tracking

• public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
• {
• // Get the HttpSession object.
• HttpSession hs = request.getSession(true);
• // Get writer.
• response.setContentType("text/html");
• PrintWriter pw = response.getWriter();
• pw.print("<B>");
• // Display date/time of last access.
• Date date = (Date)hs.getAttribute("date");
• if(date != null)
• {
• pw.print("Last access: " + date + "<br>"); }
• // Display current date/time.
• date = new Date();
• hs.setAttribute("date", date);
• pw.println("Current date: " + date);
• }
• }
• Thank You

You might also like