Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Introduction to Servlets
1. A servlet is a small Java program that runs within a Web server and used for validation
at server side. Servlets receive and respond to requests from Web clients, usually across
HTTP, the Hyper Text Transfer Protocol.
2. When a user request for a web page by entering the URL in the browser. The browser
generate HTTP request to the appropriate web server. The web server maps this request
with a specific file. The file is returned in the form of HTTP response. To handle these
request at server side we require servlet.
3.A servlet can handle multiple requests concurrently, and can synchronize requests. This
allows servlets to support systems such as on-line conferencing. Servlets can forward
requests to other servers and servlets. Thus servlets can be used to balance load among
several servers that mirror the same content, and to partition a single logical service over
several servers, according to task.
Advantages of servlet
1. Performance is significantly better. Servlets execute within the address
Space of a web server.
2.Servlets are platform independent, they are written in java. Several web
Servers, from different vendors such as Sun, Microsoft offer servlet API.
3.Java security manager on the server enforces a set of restrictions to protect
the resources on a server machine.
4.The full functionality of java class libraries is available to a servlet.
Servlets have the following advantages over the other contemporary technologies.
1. Capable of running in process
Servlets are capable of running in the same process space as the server. This offers
significant performance advantages over many competing technologies like CGI in which
each and every client request runs as a separate process. Because servlets run in process,
they need to be loaded once (at server startup or when first invoked).
2. Compiled
Unlike scripting languages, servlets are compiled into Java byte codes. By virtue of their
Compilation, Java servlets can execute more quickly than common scripting languages.
Compilation offers the advantages of strong error and type checking and many critical
errors will be flushed out during compilation time itself. Also the compiled code is more
compact and secure than non-compiled options.
3. Crash resistant
The servlets are run inside the JVM of the server. The JVM does not allow servlets direct
access to the memory locations thereby eliminating crashes that result from invalid
memory accesses (like errant pointers in C). Also the JVM will propagate an exception
up the calling chain rather than crashing, and thus even a poorly coded servlet cannot
crash the server.
4. Cross-platform
They are also platform independent just like any other normal Java program.
5. Cross-server
servlets can be run on virtually every popular web server available in the market today.
Even for servers like IIS, which does not support servlets, there are numerous plugins
available (like Jrun) in the market.
6. Durable
Servlets remain in the memory unless and until they are specifically instructed to be
destroyed. So the servlets need to be instantiated only once in order to serve a number of
requests.
7. Dynamically loadable across the network
servlets can be dynamically loaded either locally or from across the network. This is a
very great advantage for distributed computing environments. And similar to applets,
servlets run in a secure sandbox on the server to ensure security and stability.
8. Extensible
The support for Java from vendors is really over-whelming and many third party support
class libraries are emerging daily and these can be utilized by the servlets.
9. Multithreaded
Servlets support multi-threaded functionality. This allows client requests to be handled by
separate threads within a single process. This makes the execution faster than creating a
separate process for every request.
10. Protocol independent
Though servlets are normally used with HTTP protocol, they can be specially constructed
to support FTP, Telnet etc., very easily.
11. Secure
Servlets are secure in three different ways.
1. Since they are written in Java, direct memory access calls and other violations are not
possible.
2. Servlets use the security manager of the server for enforcement of certain security
policies. The security manager can restrict access of files to un-trusted servlets.
3. Lastly, servlets combine with SSL to give a full-fledged secure communication over
the net.
Life cycle of a servlet
Servlets life cycle consists of three phases. They were
a. Initialization phase.
b. Service phase.
c. Destruction phase.
Initialization and destruction typically performed once, and service performed many
times.
Initialization phase
1. It of the Servlet life cycle and represents the creation and initialization of resources the
Servlet may need to service requests.
Options method
It is used to find out what options (e.g., methods) a server or resource offers.
Head method
It is used to get a response with all headers that would be generated by a GET request, but
without the body. It can be used to make sure a link is valid or to see when a resource was
last modified.
Put method
It is used to store the message body content on the server as a resource identified by the
URI.
DELETE
The DELETE method is used to delete the resource identified by the URI.
TRACE
The TRACE method is used for testing the communication between the client and the
server. The server sends back the request message, exactly as it was received, as the body
of the response.
Note that these methods are not normally used in a web application.
Destruction phase
1. It of the Servlet life cycle represents when a Servlet is being removed from use by a
container.
2. The Servlet interface defines the destroy() method to correspond to the destruction
life cycle phase.
3. Each time a Servlet is about to be removed from use, a container calls the destroy()
method, allowing the Servlet to gracefully terminate and tidy up any resources it might
have created. By proper use of the initialization, service, and destruction phases of the
Servlet life cycle, a Servlet can efficiently manage application resources. During
initialization a Servlet loads everything it needs to use for servicing requests. The
resources are then readily used during the service phase and can then be cleaned up in the
destruction phase.
Note
1. Life cycle governs the multi-threaded environment that Servlets run in and provides an
insight to some of the mechanisms available to a developer for sharing server-side
resources.
2. When a user enters a URL to a web browser, the browser generates an HTTP request
for the URL and sends it to the appropriate server. The web server receives this HTTP
request. The web server maps this request with a particular servlet. The servlet is
dynamically retrieved and loaded into the address space of the web server. Then server
invokes init( ) method of the servlet. This method is invoked when the servlet is first
loaded into memory. Here the initialization parameters are passed to the servlet.
3. The server then invokes the service method of the servlet to process the HTTP
request. Servlet will read the data provided to it in the form of HTTP request and also
formulate it. The servlet remains in the servers address space and is available for any
HTTP request.
4. When the servlet is unloaded from the server, then destroy( ) method is called by
the server to relinquish resources
Servlet Configuration
1. It is necessary to provide initial configuration information for Servlets. Configuring
Servlets using web.xml.
2. Configuration information for a Servlet may consist of a string or a set of string values
included in the Servlets web.xml declaration. This functionality allows a Servlet to have
initial parameters specified outside of the compiled code and changed without needing to
recompile the Servlet.
3. Each servlet has an object associated with it called the ServletConfig. This object is
created by the container and implements the javax.servlet.ServletConfig interface.
4. It is the ServletConfig that contains the initialization parameters. A reference to this
object can be retrieved by calling the getServletConfig() method. The ServletConfig
object provides the following methods for accessing initial parameters:
5. In fact, in the standard Servlet library a Servlet and a ServletConfig are the same object
that is, GenericServlet implements both javax.servlet.Servlet and
javax.servlet.ServletConfig.
JSDK
1. It means java software development kit (Java Servlet Development Kit) contains the
class libraries that you will need to create servlet. JSDK is available from the Sun
Microsystems web site at java.sun.com.
2. It can be downloaded from the Sun's Web site (http://java.sun.com/j2se/1.4)
3. For JSDK documentation refer http://java.sun.com/j2se/1.4/docs.html
4. JSDK consists of number of tools that help in executing the java programs. They were
a. Applet Viewer.
b. Java Interpreter.
c. Java Compiler.
d. Java Dissembler.
e. Javadoc Tool (Documentation Generator).
f. Java Debugger.
Applet Viewer
Applets are programs written in Java that are designed to run embedded in an HTML
document, just like a Web page. Under most circumstances, they don't have the capability
to run by themselves. The Applet Viewer tool is a small program that lets you run applets
without having to launch a Web browser each time you want to test your applet code.
Java Interpreter
It is used to run your compiled Java application.
Syntax for the interpreter
java [-options] class [args...]
Where class only includes the name of the class and not the extension (.class). If the class
belongs to a package, the class name should include the fully qualified package name
with the class.
Java Compiler
It is the tool you use to compile. Java files into class files that can be run by the
interpreter.
javac <options> <sourcefiles>
Java Dissembler (javap)
It is used to disassemble Java byte code that has already been compiled. After
disassembling the code, information about the member variables and methods is printed.
The syntax for the Java dissembler is javap <options> <classes>
Multiple classes can be disassembled. Use a single space to separate each class.
The javadoc Tool (Documentation Generator)
It creates an HTML file based on the tags that are embedded in the /** */ type of
comments within a Java source file. These HTML files are used to store information
about the classes and methods that you can easily view with any Web browser.
javadoc [options] [ packagenames ] [sourcefiles] [classnames] [@files]
javadoc was actually used by the creators of the SDK to create the Java API
Documentation. The javadoc homepage can be found at
http://java.sun.com/products/jdk/javadoc/index.html
Java Debugger (jdb)
The Java debugger is the debugging tool for the Java environment and is completely
command-line driven. You can use the debugger to debug files located on your local
system or files that are located on a remote system. For remote Java files, the jdb must be
used with the -host and -password options described in the table of options.
Servlet API Documentation
1. The Java Servlet API is a set of Java classes that define a standard interface between a
Web client and a Web servlet. Client requests are made to the Web server, which then
invokes the servlet to service the request through this interface.Or
Servlet API means Servlet application programming interface. Or
Servlet API consists of set of classes and interfaces for creating servlets.
2. The Java Servlet API is a Standard Java Extension API, meaning that it is not part of
the core Java framework, but rather, is available as an add-on set of packages using the
Java Servlet Development Kit API (JSDK) V2.1 conventions.
3. The API is composed of two packages
a. javax.servlet
b. javax.servlet.http
4. The javax.servlet package contains classes to support generic protocol-independent
servlets that can be used for many protocols example, HTTP and FTP.
5. The javax.servlet.http package extends the functionality of the base package to include
specific support for the HTTP protocol.
6. The Servlet interface class is the central abstraction of the Java Servlet API. This class
defines the methods which servlets must implement, including a service() method for the
handling of requests.
7. The GenericServlet class implements this interface, and defines a generic, protocolindependent servlet. To write an HTTP servlet for use on the Web, we will use an even
more specialized class of GenericServlet called HttpServlet.
7. HttpServlet provides additional methods for the processing of HTTP requests
such as GET (doGet method) and POST (doPost method). Although our
servlets may implement a service method, in most cases we will implement
the HTTP specific request handling methods of doGet and doPost.
Description
Servlet
ServletConfig
ServletContext
ServletRequest
ServletResponse
Javax.servlet classes
Class
GenericServlet
ServletInputStream
ServletOutputStream
ServletException
Description
Implements the Servlet and ServletConfig
Provides an input stream for reading requests from a client
Provides an output stream for writing responses to a client.
Indicates that a servlet error occurred.
ServletConfig Interface
ServletContext getServletContext
getInitParameterNames()
ServletContext interface
getAtrribute(String attr)
String getServiceInfo()
Servlet getServlet(String sname)
getServletNames()
ServletRequest Interface
String getParameter(String pname)
GetParameterNames ()
String[ ] getParameterValues ()
String getProtocol ()
String getServerName ()
Int getServerPort ()
ServletResponse Interface
PrinterWriter grtWriter()
ServletOutputStream getOutputStream()
GenericServlet class
This class implements Servlet and ServletConfig interfaces
ServletInputStream class
It extends InputStream. It is implemented by the server and provides an input stream that
a servlet developer can use to read the data froma client request. In addition to this, one
more method is added which returns the actual number of bytes read
Int readLine(byte[ ] buffer, int offset, int size)
ServletOutputStream class
It extends OutputStream. It defines the print() and println() methods, which output data to
the stream.
ServletException class
It indicates that a servlet problem has occurred. It has the following constructors.
a. ServletException( )
b. ServletException(String s)
Javax.servlet.http package
It contains the classes that are extended when creating HTTP-specific servlets.
HttpServlet Class
It extends GenericServlet. It is commonly used when developing servlets that receive and
process HTTP requests. Following are the methods used by HttpServlet class.
Method
Void doGet (HttpServletRequest req,
HttpServletResponse res)
Void doPost(HttpServletRequest req,
HttpServletResponse res)
Void service(HttpServletRequest req req,
HttpServletResponse res)
Description
Performs an HTTP GET
Performs and HTTP POST
Called by the server when and HTTP
request arrives for this servlet.
Username=abcd
Valid user
Password=abcd
1.Write a program for passing initial parameter to servlet using servlet configuration file.
List of files and folders
1.C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sp
2.C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sp\WEB-INF
3. C:\Program Files\Apache Software Foundation\Tomcat
5.0\webapps\para\exampleform.html
4. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sp\WEBINF\classes
5. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sp\WEBINF\classes\sp.java
sp.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sp extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String greeting=getServletConfig().getInitParameter("greeting");
out.println("<html>"+"<head>"+"<title>"+greeting+"</title>"+"</head>");
out.println("<h1>" +greeting+"</h1>");
out.println("</html>");
}
}
web.xml
<web-app>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>sp</servlet-class>
<init-param>
<param-name>greeting</param-name>
<param-value>Servlet Configuration get init parameter</param-value>
</init-param>
Output
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
</web-app>
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("</head>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
Input
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>exampleform</welcome-file>
</welcome-file-list>
</web-app>
exampleform.html
<html>
<head><title>Example HTML Form</title></head>
<body>
<p>Shows the choosed options when you submit</p>
output
7. Occurrences of context-param tags should appear before any Servlet tags. A helpful
use of application context parameters is specifying contact information for an
application's administration.
1. Write a program for demonstrating a program for servlet context.
List of files and folders
1. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sc
2. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sc\WEBINF\web.xml
3. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\sc\WEBINF\classes\sc.java
sc.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sc extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext sc=getServletConfig().getServletContext();
String s1= sc.getInitParameter("admin email");
out.print("Servlet context used globally"+s1);
}
}
web.xml
<web-app>
<context-param>
<param-name>admin email</param-name>
<param-value>.My mail is powersamudra.@gmail.com</param-value>
</context-param>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>sc</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
</web-app>
Note
1. The power behind Servlets comes from the use of Java as a platform and from
interaction with a Servlet container.
2. The Java platform provides a Servlet developer with a robust API, object-orientated
programming, platform neutrality, strict types, garbage collection, and all the security
features of the JVM.
3. Servlet container provides life cycle management, a single process to share and
manage application-wide resources, and interaction with a Web server. Together this
functionality makes Servlets a desirable technology for server-side Java developers.
4. Java Servlets is currently in version 2.4 and a part of the Java 2 Enterprise Edition
(J2EE). Downloads of the J2SE do not include the Servlet API, but the official Servlet
API can be found on Sun Microsystems' Servlet product page,
http://java.sun.com/products/servlets, or bundled with the Java 2 Enterprise Edition.
5. Servlets are most popularly used for generating dynamic content on the Web and have
native support for HTTP.
6. Java Community Process, http://www.jcp.org, but the official reference
implementation of the Servlet API is open source and available for public access through
the Tomcat project, http://jakarta.apache.org/tomcat.
Using cookies session Tracking
Need for session Tracking
The Web protocol, HTTP, was designed to be stateless to keep transactions between a
browser and server brief and cut down on the overhead of keeping connections open.
Stateless means that after a transaction takes place between the browser and server, the
connection is lost and neither the browser nor server have any recollection of what
transpired between one session and the next. But as the Internet grew and people started
filling up shopping carts with all kinds of goodies, ordering everything from groceries to
music, books, prescription drugs, and even cars and homes, it became necessary for
merchants to remember what their customers purchased, their preferences, registration
numbers, IDs, and so on. Enter Netscape way back in 1994 with the cookie. A cookie is a
local file used to store information, and it is persistent; that is, it is maintained between
browser sessions and remains even when the user shuts down his computer. The cookie
idea became very popular and is now supported by all major browsers.
The term "cookie" comes from an old programming trick for debugging and testing
routines in a program. A text file, called a "magic cookie" was created. It contained text
that was shared by two routines so that they could communicate with each other. The
cookie feature started by Netscape[1] is also just a little piece of textual data that is stored
in a file (often called the cookie jar) on the hard drive of the client (browser). It contains
information about the viewer that can be retrieved and used at a later time to welcome
him to your site, and based on past visits, show him a new book by his favorite author,
display the latest stock quotes, or take him to CNN Europe when he wants to view the
news. The HTTP server sends the cookie to the browser when the browser connects for
the first time and from then on, the browser returns a copy of the cookie to the server
each time it connects. The information is passed back and forth between the server and
browser via HTTP headers.
A cookie is a piece of data passed between a Web server and a Web browser. The Web
server sends a cookie that contains data it requires the next time the browser accesses
the server. This is one way to maintain state between a browser and a server.
The Cookie Servlet demonstrates a servlet that gets and sets a cookie stored at a client.
Initially, the browser may not have sent the cookie as part of the request, (for example,
the first time it is called), so we just initialize a local called Count variable to 0. If we
are able to get this cookie from the request, we set the local called Count to the value of
the cookie.
The servlet first tries to get the called Count by iterating through the cookies it received
as part of the request. If no cookie contains the called Count item, then the servlet
initializes the called Count value to 0. This value is then incremented, and a new cookie
instance is created for called Count and added to the response.
If we call this servlet from a URL, we find that the first time we call it, the Called Count
is 0. Subsequent calls to the same servlet from this Web browser will show that we keep
incrementing the counter, and storing it into the cookie sent back to the browser.
This is one way by which we can maintain state between the Web browser and the
server. The major drawback with cookies is that most browsers enable the user at the
client machine to deactivate (not accept) cookies.
Class
Cookie
HttpServlet
Description
Allows state information to be stored on a client machine
Provides methods to handle HTTP requests and responses
HttpServletRequest Interface
Cookie[ ] getCookies
String getMethod()
String getQueryString()
String getRemoteUser()
String getRequestedSessionId()
String getServletPath()
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 users machine via the addCookie() method of the HttpServletResponse interface.
The names and values of cookies are stored on the users machine. Some of the
information that is used saved includes the cookies.
1.Name
2.Value.
3.Expiration date
4.Domain and path.
Following are the methods that are used by the Cookie class
String getComment()
Returns the comment
String getDomain()
Returns the domain
Int getMaxAge()
Returns the age
String getName()
Returns the name
String getPath()
Returns the path
Boolean getSecure()
Returns true if the cookie is secure
Int getVersion()
Returns the version
Void setComment(String c)
Sets the comment to c
Void setDomain(String d)
Sets the domain to d
Void setPath(String p)
Sets the path to p
Void setSecure(boolean secure)
Sets the security flag to secure
Handling HTTP Requests and Responses
Example 22: Servlet program handling HTTP GET requests
import java.io.*;
import javx.servlet.*;
import javax.servlet.http.*;
public class GetServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
String name=req,getParameter(name);
res.setContentType(text/html);
PrintWriter pw=res.getWriter();
pw.println(The Name is );
pw.println(name);
pw.close();
}
Note: Same program you can use for Handling HTTP POST requests instead of using
doGet we can use doPost