Está en la página 1de 20

UNIT 5

Tomcat web server


1. It is used for running the servlets and JSP server side scripting languages.
I.e. it is used for validating the scripts at the server side.
2. Tomcat is part of the open source Apache Jakarta project and is freely available for
download from http://jakarta.apache.org/tomcat.
3. Tomcat can be run on Windows, Linux, Macintosh, Solaris, and most any of the other
Unix distributions.
4. You can use Tomcat both commercially and non-commercially as specified by the
Apache Software Foundation License.
5. To run tomcat web server on windows we have to install two soft wares they were
a. JSDK.
b. Tomcat software
Installing Jakarta Tomcat 5 on Windows
1.To run tomcat web server on windows we have to install two soft wares they were
a. JSDK.
b. Tomcat software
2. Next we have to set the path for both JSDK and Tomcat software.
Java Path Setting
Installation of JSDK software next follow the below steps.
1.open my computer properties.
2.click advanced tab.
3.click environmental properties.
4.In user variables click new.
5.variable name=path
Variable value=C:\j2sdk1.4.2_04\bin
Tomcat Path Setting
Installation of tomcat software next follow the below steps.
1. Open my computer properties.
2. Click advanced tab.
3. Click environmental properties.
4. In user variables click new.
5. Variable name=classpath
Variable value=C:\Program Files\Apache Software Foundation\Tomcat
5.0\common\lib\servlet-api.jar
To run the Tomcat web server
1. Open Internet Explorer.
2. Type http://localhost: 8080/
or http://127.0.0.1:8080/
Java virtual machine path
C:\Program Files\Java\j2re1.4.2_04

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.

2. All Servlets must implement the javax.servlet.Servlet interface. This interface


defines the init () method to match the initialization phase of a Servlet life cycle.
3. When a container loads a Servlet, it invokes the init () method before servicing any
requests.
Service phase
It of the Servlet life cycle represents all interactions with requests until the Servlet is
destroyed. The Servlet interface matches the service phase of the Servlet life cycle to
the service() method.
2. The service() method of a Servlet is invoked once per a request and is responsible
for generating the response to that request.
3. The Servlet specification defines the service() method to take two parameters: a
javax.servlet.ServletRequest and a javax.servlet.ServletResponse object.
4. These two objects represent a client's request for the dynamic resource and the
Servlet's response to the client.
5. By default a Servlet is multi-threaded, meaning that typically a JSP container loads
only one instance of a Servlet at any given time. Initialization is done once, and each
request after that is handled concurrently by threads executing the Servlet's service()
method. This description of Servlets is slightly misleading. There are many complications
to do with loading Servlets that will be touched upon throughout this chapter and the rest
of the book.
6. Servlets require the same state synchronization required by all multi-threaded Java
objects. For simplicity, state management related issues, including proper
synchronization, before assuming you know everything about Servlets.
7. The HttpServlet object's implementation of the service() method, which is called
during each service request, calls one of seven different helper methods. These seven
methods correspond directly to the seven HTTP methods and are named as follows:
doGet(), doPost(), doPut(), doHead(), doOptions(), doDelete(), and doTrace().
The appropriate helper method is invoked to match the type of method on a given HTTP
request.
8. While all seven methods are shown, remember that normally only one of them is called
on a given request. More than one might be called if a developer overrides the methods
and has them call each other. The initialization and destruction stages of the Servlet life
cycle are the same as described before.

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.

Servlet API Documentation consists of packages


javax.servlet
The javax.servlet package contains a number of classes and interfaces
that describe and define the contracts between a servlet class and the
runtime environment provided for an instance of such a class by a
conforming servlet container.
javax.servlet.http The javax.servlet.http package contains a number of classes and
interfaces that describe and define the contracts between a servlet
class running under the HTTP protocol and the runtime environment
provided for an instance of such a class by a conforming servlet
container.
Javax.servlet.Servlet
1. It is an interface that provides the framework for all the servlets.
2. It defines five methods out of which the three most important methods are
a. init() method that initializes a servlet.

b. service() method that receives and responds to the client requests.


c. destroy() method that performs clean up.
3. It consists of two important classes that are required to build servlets. They were
a. Javax.servlet.Servlet.
b. Javax.servlet.http.
4. It contains generic interfaces and classes that are implemented and extended by all the
servlets.The two main classes are GenericServlet and HttpServlet.
5. The HttpServlet class has been extended from GenericServlet. During the development
of our own servlets, we will be extending from one of these classes.
6. The GenericServlet is an abstract class and if we extend this we have to override the
service () method. The service () method takes two arguments viz., ServletRequest and
ServletResponse. The ServletRequest object holds the information that is being sent to
the servlet whereas the ServletResponse object is where we place the data to be sent to
the client.
7. But when we extends the HttpServlet we will not extends the service() method. The
HTTP protocol uses either a GET method or POST method to invoke a servlet. So the
HttpServlet has two methods doGet () and doPost (), which takes two arguments viz.,
HttpServletRequest and HttpServletResponse. Internally the service() method of the
HttpServlet has been overridden to understand whether the request from the client has
come by either the GET/POST method and fire the appropriate method. So we have to
override either the doGet() or the doPost() method only in this case.
Interface

Description

Servlet
ServletConfig
ServletContext
ServletRequest
ServletResponse

Declares life cycle methods for a servlet


Allows servlets to get initialization Parameters
Enables servlets to log events
Used to read data from a client request
Used to read data to a client response

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.

Following are the interfaces and their methods


Method
Purpose
Void destroy
Called when the servlet is unloaded
ServletConfig getServletConfig()
Returns a ServletConfig object that Contains any
initialization parameters
String getServletInfo
Returns a string describing the servlet
Void init ()
Called when the servlet is initialized
Void service
Called to process a request from a client

ServletConfig Interface
ServletContext getServletContext

Returns the context for this servlet

String getInitParmeter(String param)

Returns the value of the initialization


parameter name param
Returns all initialization parameter names

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 ()

Returns the value of the server attribute named attr.


Returns information about the server.
Returns the servlet named sname.
Returns the names of servlets in the server
Returns the value of the parameter named pname
Returns the parameters names for this request.
Returns the parameters values for this request.
Returns a description of the protocol
Returns the name of the server.
Returns the port number.

ServletResponse Interface
PrinterWriter grtWriter()
ServletOutputStream getOutputStream()

Returns a PrintWriter that can be used to


write character data to the response
Returns a ServletOutputStream that can be
used to write binary data to the response

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.

Interfaces present in javax.servlet.http package are


Interface
Description
HttpServletRequest
Enables servlets to read data from an HTTP request
HttpServletResponse
Enables servlets to write data to an HTTP response.
HttpSession
Allows session data to be read and written
HttpSessionContext
Allows sessions to be managed
1.Write a program for reading servlet parameters and initializing the parameters of a
servlet to verify the user name and password are same or not.
List of files and folders
1. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\spup
2. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\spup\login.html
3. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\spup\WEB-INF
4. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\spup\WEBINF\web.xml
5. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\spup\WEBINF\classes
6. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\spup\WEBINF\classes\sp.java
login.html
<html>
<head><title>Reading and Initializing servlet parameters</title></head>
<body bgcolor="blue" text="yellow">
<font size="5">
<form action="/spup/hello" method="post">
<center>
User verification form<br>
Name <input type="text" name="un"><br>

Password<input type="password" name="pwd"><br>


<input value="Submit" type="submit">
</center>
</form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>sp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
sp.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sp extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String s1=req.getParameter("un");
String s2=req.getParameter("pwd");
if(s1.equals(s2))
out.println("valid user");
else
out.println("Not a valid user");
}
}
Input
Output

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>

To view output type on the server


http://localhost:8080/sp/hello
Generated Markup
HelloWorld.java
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

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>");

Form Data and Parameters


1. Anytime an HTML form is filled out and sent to a server, the fields are passed as
parameters. This includes any information sent via input fields, selection lists, combo
boxes, check boxes, and hidden fields, but excludes file uploads.
2. Any information passed as a query string is also available on the server-side as a
request parameter. The HttpServletRequest object includes the following methods for
accessing request parameters.
getParameter (java.lang.String parameter Name)
The getParameter() method takes as a parameter a parameter name and returns a String
object representing the corresponding value. A null is returned if there is no parameter of
the given name.
getParameters (java.lang.String parameter Name)
The getParameters() method is similar to the getParameter() method, but it should be
used when there are multiple parameters with the same name. Often an HTML form
check box or combo box sends multiple values for the same parameter name. The
getParameter() method is a convenient method of getting all the parameter values for the
same parameter name returned as an array of strings.
getParameterNames()
The getParameterNames() method returns a java.util.Enumeration of all the parameter
names used in a request. In combination with the getParameter() and getParameters()
method, it can be used to get a list of names and values of all the parameters included
with a request.
1. Write a program that prints the options option selected at client side by server.
List of files and folders
1. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\para
2. C:\Program Files\Apache Software Foundation\Tomcat
5.0\webapps\para\exampleform.html
3. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\para\WEBINF\web.xml

4. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\para\WEBINF\classes


5. C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\para\WEBINF\classes\showParameters.java
ShowParameters.java
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class showParameters extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Request HTTP Parameters Sent</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Parameters sent with request:</p>");
Enumeration enum = request.getParameterNames();
while (enum.hasMoreElements())
{
String pName = (String) enum.nextElement();
String[] pValues = request.getParameterValues(pName);
out.print("<b>"+pName + "</b>: ");
for (int i=0;i<pValues.length;i++)
out.print(pValues[i]);
out.print("<br>");
}
out.println("</body>");
out.println("</html>");
}
}
web.xml
<web-app>
<servlet>
<servlet-name>b</servlet-name>
<servlet-class>showParameters</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>b</servlet-name>

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

<form action="/para/hello" method="post">


Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
Select Box: <select name="selectbox">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br>
Importance: <input type="radio" name="importance" value="very">
Very, <input type="radio" name="importance" value="normal">
Normal,<input type="radio" name="importance" value="not">Not<br>
Comment: <br><textarea name="textarea" cols="40" rows="5"></textarea><br>
<input value="Submit" type="submit">
</form>
</body>
</html>
ServletContext
Initial Web Application Parameters
1. Servlet context provides initial configuration that all Servlets have access to.
2. Each Servlet has a ServletConfig object accessible by the getServletConfig() method
of the Servlet.
3. A ServletConfig object includes methods for getting initial parameters for the
particular Servlet, but it also includes the getServletContext() method for accessing the
appropriate ServletContext instance.
4. A ServletContext object implements similar getInitParam() and getInitParamNames()
methods demonstrated for ServletConfig.
5. The difference is that these methods do not access initial parameters for a particular
Servlet, but rather parameters specified for the entire Web Application.
6. Specifying application-wide initial parameters is done in a similar method as with
individual Servlets, but requires replacement of the init-param element with the contextparam element of Web.xml, and requires the tag be placed outside any specific servlet
tag.

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()

Returns an array of the cookies in this request


Returns the HTTP method for this request
Returns any query string in the URL
Returns the name of the user who issued
this request.
Returns the ID of the session
Returns the part of the URL that identifies
the servlet

HttpServletResponse Interface Methods


Void addCookie(Cookie cookie)
Adds cookie to the HTTP response.
Void sendError(int c)
Send the error code c to the client
Void sendError(int c , String s)
Send the error code c and the message s
Void sendRedirect(String url)
Redirects the client to url
Cookie class

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

También podría gustarte