Servlets Notes Unit 4
Servlets Notes Unit 4
Unit IV Servlets
Introduction to Web-Applications:
A web application is nothing but a web-site. A web application can be thought of as a collection of two types
of resources Static, Dynamic Resources. Web applications are deployed (installed) on the web servers (web-
containers) and are normally accessed through the web Clients, which is normally a web browser. The
communication between web client and web server takes place through HTTP protocol (Set of rules).
1. Static Resources:
These are normally non-executable resources. In some cases static resources may also be the executable
resources but they do not execute on the server. These are only for view purpose. A typical application might
have following types of static resources:
• HTML • Documents
• Images, Audio and Video files • Spreadsheets
• Applets • Text Files
A web client can ask for any static resource by just specifying the URL. Web server simply returns the
specified resource to the client without any processing. The client decides what to do with the static resource.
The most common static resource is the HTML page. The web browser interprets the HTML page and
displays in the browser window. For other type of static resources the action taken may differ from browser
to browser. The browser either displays the contents of the resource on its own or with the help of software
corresponding to the static resource. For example, Internet Explorer may open a .doc file using MS-word
software. The browser prompts for saving the contents in case it is not able to display/process the contents.
2. Dynamic Resources:
These are executable resources. The dynamic resources are also accessed by directly or indirectly specifying
the URL. But the action taken by web server is different in case of dynamic resources. The dynamic sources are
Java programs. The server executes the appropriate component and then returns the result to the client normally
as HTML using HTTP protocol. A web application can have following types of dynamic resources:
• CGI: Common Gateway Interface (CGI) is a technology to generate dynamic web contents. CGI enables the
web server to call an external program and pass HTTP request information to that external program to process
the request. The response from the external program is then passed back to the web server, which forwards it
RIX
AT
M
to the client browser. CGI programs can be written in any language that can be called by the web server. Perl is
a language to write CGI programs.
• Servlets: Java servlets are small, platform independent server side programs that programmatically extend the
functionality of the web server.
• Java server pages(JSPs): Java Server Pages is an extension of the java servlets technology. However, in
contrast to servlets, which are pure Java programs, JSP pages are text-based documents. A JSP page contains
two parts:
• HTML for the static content
• JSP tags and scriptlets written in java to encapsulate the logic that generate the dynamic content. Since a
JSP page provides a general representation of content that can produce multiple views depending on the
result of JSP tags and scriptlets, a JSP page acts like a template for producing content.
mean that each customer should have a copy of the program(s) in his or her PC which translates to 10,000
programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to
the database which simply cannot be handled by client side programs. The answer to most of the issues
mentioned above is – “Server Side Programming”.
Vendor Product
Apache Apache
Microsoft IIS(Internet Information Server)
Google GWS
Web Container:- It contains & manages all the web resources. It is a runtime environment for web components that
includes security, concurrency, lifecycle management, transaction, deployment, and other services.
• Sun Java System Web Server
• Tomcat for Java WSDP
The web applications are deployed on the web servers. The Web server handles all the communication between
web client and the web application. As discussed earlier a web application is simply collection of static and dynamic
resources. Any resource belonging to a web application is identified by URL. The client can access any resource by just
specifying the URL. Web server might have some common resources, which do not belong to any web application. Such
resources are normally static resources. If client asks for some resources not belonging to any application, the web
server can directly send resource to the client.
Matrix Computers (Page 3 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
If the client asks for some resource belonging to web application then it is not served directly by the web server.
Web server passes the request to the web container, which is a component responsible for running the web applications.
If the resource is static then web container simply passes the resource to the web server and then web server
sends the resource to the web client. On the other hand if the resource is dynamic then the web container executes the
resource and receives the result normally in the form of HTML and then passes the result to the web server which then
passes it to the web client.
• Safety:- As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic
garbage collection and a lack of pointers mean that servlets are generally safe from memory management
problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. It also uses
exception handling which is very efficient mechanism in error handling.
• Integration:- Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths,
perform logging, check authorization, and MIME type mapping etc.
• Extensibility:-The servlet API is designed in such a way that it can be easily extensible. As it stands today, the
servlet API support Http Servlets, but in later date it can be extended for another type of servlets.
• Inexpensive:-There are number of free web servers available for personal use or for commercial purpose. Web
servers are relatively expensive. So by using the free available web servers you can add servlet support to it.
MIME:-
MIME (Multipurpose Internet Mail Extensions) is a mechanism for Specifying and describing the format of
Internet Message Bodies. When the Web Server receives a request from a client, it uses the MIME type mappings to
determine the kind of resource that is requested. Some MIME types are:-
type=text/html gives output in text/html form
type=text/plain Plain Text
type=text/richtext Rich Text Format
type=application/vnd.ms-powerpoint Microsoft Power Point.
type=application/vnd.ms-excel Microsoft Excel.
type=application/vnd.ms-word Microsoft Word.
Note:- Use these inside setContentType("text/html") method to get output in the required form.
In this protocol, the clients always initiate requests. The Server can never make a Callback Connection to the
M
Client.
• The HTTP requires the clients to establish connections prior to each request and the servers to close the
connection after sending the response. This guarantees that the client cannot hold on to a connection after
receiving the response. Either the client or the server can prematurely terminate the connection.
Directory Structure:
The directory structure of a web application has two parts:
1. A directory WEB-INF that contains the resources, which are not to be directly downloaded to a client. This
Directory is private. The client does not have direct access to the files in this directory. The WEB-INF
directory typically contains dynamic resources such as servlets, as well as configuration files.
Matrix Computers (Page 6 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
2. A directory that contains those resources that are intended to be public ally available. This includes all the
subdirectories of this directory, except the private WEB-INF directory. This Directory typically contains
static resources such as HTML and image files. The JSP files, which have static as well as dynamic
contents, are also stored in this directory.
For example, a web-application could have the directory structure.
Private Resources- Files contained within the WEB-INF directory. These are resources that are only accessible to
the web container.
Public Resources:
A public resource is any file that is accessible to the client of the web application. Typical public resources are:
• HTML, XML and JSP
• Image, Audio and Video files.
• Java Applets- classes as well as jar files containing applets.
• Microsoft office documents: word, Excel, etc.
Client browsers can download these resources unchanged and render them as required. For example, when
an HTML page includes <APPLET> tag that refers to an applet in a jar file, the web container delivers the JAR file to
the client browser unchanged.
Typically, the container reads the static resources from the file system, and writes the contents directly to the
network connection. The interpretation of the contents of theses resources is the responsibility of the client browser. In
order to help the browser render the file correctly, the container sends the MIME type of the file. These MIME types
can be set in the deployment descriptor of the web application.
Note: Although JSP pages are included as public resources in a web application; the container does not show them
directly to clients. The container automatically converts JSP Pages into Servlets. The servlet is then compiled and
invoked to generate the response for the client. However, since a JSP Page is often considered more near to an HTML
document than a java class, JSP Pages are also included under public resources.
Private resources:
Matrix Computers (Page 7 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Private resources are certain resources that clients should not load directly. There may be files that the client
should not view, such as configuration files or they may be files that the container must perform some processing on
before sending the response to the client, like servlets. These private resources are stored in the WEB-INF directory,
or its subdirectories.
The types of resources that clients should not download directly include:
• Servlets-These components include application logic, and possibly access to other resources such as
databases.
• Any other files in the web application that servlets access directly.
• Resources that meant for execution or use on the server side, such as java class files and JAR files of classes
used by your servlets.
• Temporary files created by your applications.
• Deployment descriptors and other configuration files.
These resources are private and as such are accessible only their own web application and the container. In order to
accommodate private resources the web container requires the WEB-INF directory to be present in your application.
If your web application does not contain this directory it will not work.
6. According to the Servlet specification a container should load classes/JAR files of each web application using
a different class loader. It is for this reason that servlets, JSP Pages and other classes that are part of one web
application cannot see classes in other applications
Thus even if you deployed the same web application twice (each mapping to a different URL), as for as
container is concerned, they are two entirely different applications. Such applications cannot share information. As a
result, web containers create a virtual partitioning of web applications within the container.
Web Servers:
There are many web server’s available in industry. Some popular web server’s are:- Apache web server - the
HTTP web server, Apache Tomcat, Microsoft Windows Server 2003 Internet Information Services (IIS), Jigsaw, Sun
Java System Web Server, Bea Weblogic Server, IBM WebSphere Server. Tomcat is one of the most popular open
source web sever for deploying and running web applications
Tomcat Server:
Apache Tomcat is a Web Server not an application server. You can change port number for apache tomcat at
the time of installation. By default it listens on port number 8080. To change port number after installation
1. Open tomcat\conf directory and then open server.xml in notepad.
2. Look for the following code in server.xml:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
3. delete 8080 port number and write a new port number and save server.xml. Don’t change any other coding.
4. Now Start Tomcat and use port number given by you in server.xml.
Matrix Computers (Page 9 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
If there is any error regarding your application or any exception. To find out the errors go to Tomcat\logs
directory and search for stderror_date text file. When we use System.out.print() in web applications then it gives output
in Tomcat\logs directory’s stdout_date file. Like today is 17-march-2010 and you are running your application then
error will be present in stderr_20100317 and output will be present in stdout_20100317.
Tomcat Installation:
The installation process is described for tomcat 5.5/6.0:
1. Download the setup file (says apache tomcat 6.0.20.exe) from the apache web site.
2. Make sure J2SE is installed on your machine. If JDK (J2SE) is installed in directory c:\JDK1.6 then the
environmental variable JAVA_HOME should be set to c:\JDK1.6 but it is not mandatory.
3. Double click on the setup-file to install the tomcat. The installer will guide you through the entire installation
process.
4. When it asks for destination folder you can specify any location (like C:\Tomcat 6.0 or D:\Tomcat6.0). This
directory is known as tomcat’s home directory. The CATALINA_HOME environment variable points to this
folder.
5. The installer then asks for port number, username and password. The default port number is 8080; you can
change it or make it your port number. The default user name is admin, you can also change it. And insert your
password.
6. The installer then asks of the path of J2SE (JDK) or JRE (Java Runtime Environment) installed on the machine.
By default Tomcat selects path form JAVA_HOME or you can choose path to another JRE installed on your
machine.
So if Tomcat is installed in C:\Tomcat6.0 and JDK is installed in C:\JDK6.0 The environmental variable
CATALINA_HOME= C:\Tomcat6.0
JAVA_HOME= C:\JDk6.0
JBoss Server:
JBoss is an application server, it is build upon tomcat server. To handle web application JBoss internally uses
tomcat server.
1. To install JBoss double click on installer.jar file or use command
java –jar installer.jar.
2. Select language English and
3. click next->next->next
4. To uninstall JBoss double click on uninstaller.jar or use java –jar uninstaller.jar command.
Suppose you installed JBoss in C:\Program Files\jboss-4.0.4RC1 directory then the home directory for JBoss is jboss-
4.0.4RC1.
1. Double click on bin\run.bat or run.jar file to start JBoss Server.
2. To stop the server just use ctr+c on DOS window on which server is started..
3. Deploy or create applications in \server\default\deploy directory structure.
4. If you are creating application in \server\default\deploy directory itself then use war extension with your
application, the rest process is same as creating application using Tomcat.
Matrix Computers (Page 10 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
JBoss also listens port number 8080, to change port number go to \server\default\deploy\jbossweb-
tomcat55.sar and open server.xml in notepad to change port number. The code in server.xml may be like this:
<Connector port="8080" address="${jboss.bind.address}"
maxThreads="250" strategy="ms" maxHttpHeaderSize="8192"
emptySessionPath="true"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"/>
Note You must ensure that you have a JAVA_HOME environment variable that points to the location of the directory
where you installed J2SE JDK.
Like JAVA_HOME
C:\Program Files\Java\jdk1.6.0_01
Example:-
PrintWriter out=response.getWriter();
out.print(“name”);
out.print(“<br>”);
out.print(“fname”);
out.close();
Note:- After use close the PrintWriter object using close() method.
Port:-
A port is a connection between a server and a client. Ports are identified by positive integers. Port is a software
notion, not a hardware notion, so there may be many of them. A service is associated with a specific port
Typical port numbers:
21—FTP, File Transfer Protocol
25—SMTP, Simple Mail Transfer Protocol
RIX
AT
M
4. <servlet-name>Testing</servlet-name>
5. <servlet-class>TestingApp</servlet-class>
6. </servlet>
7. <servlet-mapping>
8. <servlet-name>Testing</servlet-name>
9. <url-pattern>/testingapp</url-pattern>
10. </servlet-mapping>
11. </web-app>
TestingApp.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class TestingApp extends HttpServlet
5. {
6. public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
7. {
8. ServletContext sc=getServletContext();
9. String nm=sc.getServletContextName();
10. String username=request.getParameter("username");
11. String password=request.getParameter("password");
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14. out.print("<html>");
15. out.print("<body>");
16. out.print("Username is "+username);
17. out.print("<br>");
18. out.print("Passwod is "+password);
19. out.print("<br>");
20. out.print("Display Name is "+nm);
21. out.print("</body>");
22. out.print("<html>");
RIX
AT
M
23. out.close();
24. }
25. }
Step 2: Write code for index.html and save/copy it into folder testingapp
Step 3: Write code for TestingApp.java servlet and save\copy it into src folder.
Step 4: Compile the TestingApp.java file (servlet) so that the package hierarchy is created in the WEB-
INF/classes folder.
javac –d D:\matrix\testingapp\WEB-INF\classes TestingApp.java
Note: - While compiling, make sure that either j2ee.jar or servlet.-api.jar file is in classpath.
The server-api.jar file will be present in the C:\Tomcat6.0\lib
Step 5: Write code for web.xml and save it in WEB-INF folder.
Step 6: Copy the testingapp from D:\matrix\testingapp and paste into C:\Tomcat6.0\webapps.
Step 7: Start the Tomcat Server.
Here http stands for Http Protocol, localhost is server address, You can also put 127.0.0.1 (IP Address) instead of
localhost, 8080 is port number.
Load on Startup:
<servlet>
<servlet-name>.................</servlet-name>
<servlet-class>.................</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
The load-on-startup element is used to load the servlet automatically into memory when the web container
starts up. Loading a servlet means instantiating the servlet and calling its init method. You use this element to avoid
delay in the response for the first request to the servlet, caused by the servlet loading to memory.
The content of a load-on-startup value is either empty or an integer number. The value indicates the order of
loading into memory by the web container. For example, if there are two servlet elements and both contain load-on-
startup sub-element, the servlet with a lower number in the load-on-startup sub-element is loaded first. If the value of
the load-on-startup is empty or a negative number, it is up to the web container to decide when to load the servlet. If
two servlets have the same value for their load-on-startup sub-elements, the web container is free to choose which
servlet to load first.
Welcome Files:
index.html, index.jsp and index.htm are default welcome files for your application. You can change welcome
file using web.xml.
Code:
<web-app>
<welcome-file-list>
<welcome-file>myfile.html</welcome-file>
<welcome-file>yourfile.html</welcome-file>
</welcome-file-list>
</web-app>
If you are using the above code and myfile.html is available then welcome page will be myfile.html not index.html. If
myfile.html is not present the yourfile.html will be displayed as welcome page. If both files myfile.html and yourfile.html
are not available then welcome page will not be displayed. By default index.html will not be displayed in this case
otherwise if welcome tag is missing then server will display index.html file by default.
RIX
AT
M
Context parameters:
<web-app>
<context-param>
<param-name>address</param-name>
<param-value>Mansarovar</param-value>
</context-param>
</web-app>
The <context-param> tag should be child tag of <web-app> tag because it is for whole application. These are available
for all the servlets of your application.
Init Parameters:
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>faculty</param-name>
<param-value>XYZ</param-value>
</init-param>
</servlet>
The <init-param> tag should be child tag of <servlet> tag because init parameters are servlet specific parameters.
These are available in defined servlet only (like in MyServlet only) not in other servlets.
Matrix Computers (Page 15 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
ServletContext context=getServletContext();
and
ServletConfig config=getServletConfig();
String name= config.getInitParameter(“name”);//for init parameters
String course= context.getInitParameter(“course”);// for context/application parameters
Note:-<init-param> two times with same name application will work properly.
1. Different name, Different value Ok.
2. Different name, Same value Ok.
3. Same name ,Same value Ok.
4. Same name, Different Value Ok. The second init-param’s value will be considered.
RIX
AT
M
RIX
AT
M
Matrix Computers (Page 18 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
1. Instantiation/Loading: The Web Container creates an instance of the servlet and loads it. When the
Web container is started it loads and initializes the Servlet. The Web container may
delay this stage until the Web container determines which servlet is needed to service
a request. Servlet container loads the Servlet class by using the normal Java class
loading option. Moreover, the servlet class may be loaded from a local file system, a
remote file system, or other network services. If the servlet containers fails to load the
class, it terminates this process. After loading container creates an instance of the
Servlet. If the Servlet does not inherits SingleThreadModel interface then only one
object of Servlet will be created and a seprate thread for each request is started on
this object.
2. Initialization: The Container calls the instance’s init( ) method, which accepts the ServletConfig
object reference as a parameter. This object allows the Servlet instance to access
name-value configured initialization parameters and other container specific details.
The Servlet container creates one ServletConfig object per Servlet declaration in the
deployment descriptor.
3. Service: If the Container has a request for the servlet it calls the servlet instance’s service( )
method.
4. Destroy: Before destroying the instance, the container calls the servlet instance’s destroy ( )
method. After this servlet instance is garbage collected.
5. Unavailable: The instance is marked as unavailable. The unavailable may be temporary or
permanent.
Web servers with Java servlet implementation, such as Tomcat, Weblogic, JBoss etc. use most of the
interfaces and classes in the above table. In fact apart from the various listener interfaces, there is only one class
(javax.servlet.http.HttpServlet) and one interface (javax.servlet.Filter) that are left for you to implement when building
web applications.
The container creates the rest of the runtime objects that are part of your application. Why is this so? A web
container is an application framework with a runtime environment. In the Framework, application objects are created
and invoked by the runtime. While invoking methods on the application objects, the container has to construct the
objects of the arguments. For example, in TestingApp servlet, the container creates and passes the HttpServletRequest
and HttpServletResponse objects as arguments to the service() method.
In the same fashion, the container creates all other objects (such as ServletContext, ServletConfig,
HttpSession and so on) that a servlet can access directly or indirectly.
javax.servlet.httpServlet classes. When implementing the javax.servlet.Servlet interface, the following five
methods must be implemented:
• public void init(ServletConfig config)
• public void service(ServletRequest request, ServletResponse response)
• public void destroy( )
• public ServletConfig getServletConfig( )
• public string getServletInfo( )
original request data, and the response object provides methods with which the servlet can build a response.
This method will be called again & again for every request from different users.
10. </web-app>
Output:-
Output of this program will be shown in stdout_date file in C:\Program Files\Apache Software
Foundation\Tomcat 6.0\logs folder.
Note:- When you are implementing Servlet Interface implement all the methods of Servlet Interface.
Note:- If same servlet is register two times, application doesn’t start. means <servlet>tag two times with same
servlet-name not allowed.
Note:-Different URL Patterns for same servlet it will work properly. You can give same url-pattern to two different
servlets but it will run the second servlet.
{
private transient ServletConfig config;
public String getInitParameter(String name)
{
return config.getInitParameter(name);
}
}
• public Enumeration getInitParameterNames():- This method returns all the names of the servlet initialization
parameters as an enumeration of String objects. This method returns an empty enumeration if the Servlet does
not contain any initialization parameters.
• public ServletConfig getServletConfig():-This method returns the reference of the ServletConfig object.
Using this object we can read init-parameters from web.xml file which are servlet specific.
• public ServletContext getServletContext():-This method returns the reference of the ServletContext object.
Using this object we can read configuration parameters from web.xml file which are application specific.
• public String getServletInfo():-It returns the information about the Servlet in String format. The
implementation of this method given by GenericServlet returns an empty String.
• public void init(ServletConfig) throws ServletException:- The init (ServletConfig config) method stores
the ServletConfig object in a private transient instance variable (called config). You can use the
getServletConfig( ) method to access this object. However, if you choose to override this method, you should
include a call to super.init (config). Alternatively, you can override the overloaded no-argument init( ) method
in the GenericServlet class. If you override init(ServletConfig config) and not calling super.init(config) then
config object will not be initialized. Means you are unable to get config object through getServletConfig();
Matrix Computers (Page 25 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
• public void init() throws ServletException:- This is an alternative to init(ServletConfig). Instead of overriding
init(ServletConfig) it is easy to override init() method because we have to call super(config) in
init(ServletConfig) but in init() method there is no need to call super(config). init(ServletConfig) also calls init()
method after calling super().
• public void log(String message):- This method writes the name of the servlet and the message argument to
the web container’s log. Writes the specified message to a servlet log file. It first writes servlet's name which
is having this log(string msg)method. Tomcat home directory’s →logs directory, you will find files like
localhost.2010-04-06 in logs. Open the localhst.today’sdate.txt file to see the log message.
• public void log(String message, Throwable t):- This method includes a stack trace for the given Throwable
exception in addition to the servlet name and message. The actual implementation of the logging mechanism
is container-specific, although most of the containers use text files for logging purposes. This method writes a
message and a stack trace for a given Throwable exception to the servlet log file, by writing the servlet's name.
The log file may be having syntax like localhost.today’sdate.txt
• public abstract void service(ServletRequest,ServletResponse)throws ServletException, IOException:-
This is an abstract method which we have to override if implementing GenericServlet class.
• public String getServletName():- This method returns the name of the Servlet in String format which is written
in <servlet-name> tag of web.xml file (Deployment Descripter file).
For Example:
Overriding init(ServletConfig) method(wrongly):-
public class MyGeneric extends GenericServlet
{
public void init(ServletConfig config) throws ServletException
{
System.out.print("init method");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
System.out.print("My Generic Servlet class");
ServletConfig config=getServletConfig();
// Here config object is assigned to null because getServletConfig() method will
RIX
AT
M
//return null.
}
}
{
public void init() throws ServletException
{
System.out.print("init method");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
System.out.print("My Generic Servlet class");
ServletConfig config=getServletConfig();
// Here config object is assigned to ServletConfig object
}
}
If you are not overriding init(ServletConfig config) method. Then init(ServletConfig config) method
will be inherited into your servlet class. The inherited method init(ServletConfig config) have following
code:
pubic void init(ServletConfig config)
{
super.init(config);
init();
}
The above method have a calling statement to invoke init() method. The use of init() method (init()
with no arguments) is to simplify the initialization code without disturbing init(ServletConfig config)
method.
18. //{
19. // System.out.print("init without parameters");
20. //}
21. public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
22. {
23. ServletContext context=getServletContext();
24. ServletConfig config=getServletConfig();
25. String name=getServletName();
26. String info=getServletInfo();//This method returns an empty string
27. String param=getInitParameter("user");
28. PrintWriter out=response.getWriter();
29. out.print(name);
30. out.print(info);
31. out.print(param);
32. Enumeration en=getInitParameterNames();
33. while(en.hasMoreElements())
34. {
35. out.print(en.nextElement());
36. }
37. log("You will get it in localhost.txt of Tomcat logs folder");
38. log("You get it in localhost.txt with an exception in logs folder of Tomcat", new Exception());
39. }
40. }
web.xml
1. <web-app>
2. <display-name>GenericServlets</display-name>
3. <servlet>
4. <display-name>MyGeneric</display-name>
5. <servlet-name>MyGeneric</servlet-name>
6. <servlet-class>com.matrix.MyGeneric</servlet-class>
7. <init-param>
RIX
AT
M
8. <param-name>user</param-name>
9. <param-value>Matrix</param-value>
10. </init-param>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>MyGeneric</servlet-name>
14. <url-pattern>/generic</url-pattern>
15. </servlet-mapping>
16. </web-app>
Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST
method allows the client to send data of unlimited length to the Web server a single time and is useful when
posting information such as credit card numbers If the HTTP POST request is incorrectly formatted, doPost
returns an HTTP "Bad Request" message.
1. <html>
2. <body>
3. <form method=get action=servlet1>
4. Firstname <input type=text name=firstname value=""><br>
5. Lastname <input type=text name=lastname value=""><br>
6. E-mail Id <input type=text name=email value=""><br>
7. Mobile No <input type=text name=mobile value=""><br>
8. <input type=submit value=Submit>
9. </form>
10. </body>
11. </html>
Servlet11.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String firstname=request.getParameter("firstname");
14. String lastname=request.getParameter("lastname");
15. String email=request.getParameter("email");
16. String mobile=request.getParameter("mobile");
17. out.print("Welcome : ");
18. out.print(firstname);
19. out.print("<br>");
RIX
AT
M
Output:-
Matrix Computers (Page 30 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
RIX
AT
M
Example 5 JDBC Demo, Servlets are like core java classes. Accessing database using JDBC in servlet is same as
accessing JDBC in simple core java application. The following web application is interacting with Database using JDBC:
register.html
1. <html>
2. <head>
3. <title>JDBC Demo</title>
4. </head>
5. <body>
6. <center>
7. <form method=post action=register>
8. <h2><font color=blue>Matrix Research and Computer Education</font></h2>
9. <h3>Welcome to Login Page</h3><br><br>
10. <table border=1 width=300 cellpadding=4 cellspacing=4>
11. <tr>
12. <td>Username</td>
13. <td><input type=text name=username size=30 maxlength=30></td>
14. </tr>
15. <tr>
16. <td>Password</td>
17. <td><input type=password name=password size=30 maxlength=30></td>
18. </tr>
Matrix Computers (Page 31 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
19. <tr>
20. <td>E-Mail</td>
21. <td><input type=text name=email size=30 maxlength=40></td>
22. </tr>
23. <tr>
24. <td></td>
25. <td> <input type=submit value=Register></td>
26. </tr>
27. </table>
28. <br>
29. </form>
30. <hr>
31. <br><a href=view.html>Click to View Details</a><br>
32. </center>
33. </body>
34. </html>
view.html
1. <html>
2. <head>
3. <title>View Student Details</title>
4. </head>
5. <body>
6. <center>
7. <form method="post" action="viewdetails">
8. <h2><font color="blue">Matrix Research and Computer Education</font></h2>
9. <h3>Welcome to View Page</h3><br>
10. <table>
11. <tr>
12. <td>Username</td>
13. <td><input type="text" name="username" size=30></td>
14. </tr>
15. <tr>
RIX
AT
M
16. <td></td>
17. <td><input type="submit" value="View Details"></td>
18. </tr>
19. </table>
20. </form>
21. <br><a href=register.html>Go to Home Page</a>
22. </center>
23. </body>
24. </html>
RegisterDetails.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.SQLException;
7. import java.sql.Statement;
8. import javax.servlet.ServletException;
9. import javax.servlet.http.HttpServlet;
10. import javax.servlet.http.HttpServletRequest;
11. import javax.servlet.http.HttpServletResponse;
12. public class RegisterDetails extends HttpServlet
13. {
14. protected void doPost(HttpServletRequest request, HttpServletResponse response)
Matrix Computers (Page 32 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
47. }
48. finally
49. {
50. try
51. {
52.
53. stmt.close();
54. }
55. catch(SQLException ex)
56. {
57.
58. }
59. try
60. {
61. con.close();
62. }
63. catch(SQLException ex)
64. {
65.
66. }
67. }
68. }
69. }
ViewDetails.java
Matrix Computers (Page 33 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.ResultSet;
7. import java.sql.SQLException;
8. import java.sql.Statement;
9. import javax.servlet.ServletException;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13. public class ViewDetails extends HttpServlet
14. {
15. protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
16. {
17. int count=0;
18. String username=request.getParameter("username");
19. PrintWriter out=response.getWriter();
20. Connection con=null;
21. Statement stmt=null;
22. ResultSet rs=null;
23. try
24. {
25. Class.forName("com.mysql.jdbc.Driver");
26. }
27. catch(ClassNotFoundException ex)
28. {
29. ex.printStackTrace();
30. }
31. try
RIX
AT
M
32. {
33. con=DriverManager.getConnection("jdbc:mysql://localhost:3306/matrix","root","root");
34. stmt=con.createStatement();
35. String query="select * from register where username='"+username+"'";
36. rs=stmt.executeQuery(query);
37. while(rs.next())
38. {
39. username=rs.getString("username");
40. String password=rs.getString("password");
41. String email=rs.getString("email");
42. out.print("<center><h2> Your Username is:"+username);
43. out.print("<br>Your Password is: "+password);
44. out.print("<br>");
45. out.print("Your E-Mail is:"+email+"</h3>");
46. out.print("<br><br>");
47. count++;
48. out.print("<a href=view.html>Go Back</a>");
49. }
50. if(count==0)
51. {
52. out.print("<h2>No Record Found<br>");
53. out.print("<a href=view.html>Try Again.... </a></h2>");
54. }
55. }
Matrix Computers (Page 34 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
3. <servlet-name>RegisterServlet</servlet-name>
4. <servlet-class>com.matrix.RegisterDetails</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>RegisterServlet</servlet-name>
8. <url-pattern>/register</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>view</servlet-name>
12. <servlet-class>com.matrix.ViewDetails</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>view</servlet-name>
16. <url-pattern>/viewdetails</url-pattern>
17. </servlet-mapping>
18. <welcome-file-list>
19. <welcome-file>register.html</welcome-file>
20. </welcome-file-list>
21. </web-app>
Query in database
Mysql:
create database matrix;
use matrix;
create table register(username varchar(30) unique key not null, password varchar(30), email varchar(30));
Matrix Computers (Page 35 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Oracle:
Driver name: oracle.jdbc.driver.OracleDriver
URL: jdbc:oracle:thin:@localhost:1521:orcl
Create database matrix or database that you are using in your program.
create table register(username varchar2(30), password varchar2(30), email varchar2(30));
OutPut:-
RIX
AT
M
Matrix Computers (Page 36 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Note:- In above program instead of overriding service() method we can also define doPost() method.
affect the performance. For each incoming request, the container allocates a Servlet instance from the pool,
and upon completion of the service, the container returns the instance to the pool.
• Request Serialization:-
In this approach, the container maintains a single instance of the servlet. However, since the container
cannot send multiple requests to the instance at the same time, the container serializes the requests. This
means that new requests will be kept waiting while the current request is being served.
Note that the SingleThreadModel is resource intensive, particularly if a large no. of concurrent requests
is expected for the servlet. The effect of the SingleThreadModel is that the container invokes the service ( )
method in a synchronized block. This is equivalent to using the synchronized keyword for the servlet’s service
( ) method. Accordingly, when there are hundreds or even thousands of concurrent requests to the web
container, the container may either serialize requests to the same instance of the servlet, or create that many
hampered due to serialization. In the later case, the container encounters more object allocation (which
includes more object creation overhead and memory usage).
However, in cases where only a few statements of the service ( ) method are not thread safe, you
should consider reducing the scope of synchronization of the service ( ) and explicitly synchronize such blocks
Matrix Computers (Page 37 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
using the synchronized keyword. Depending on how short such synchronization blocks are, this approach
could improve performance.
Note: - We should always consider redesigning our applications in order to avoid the
SingleThreadModel or thread synchronization. If we cannot avoid them, it is important to be aware of the
performance implications. With any thread synchronization code, you are potentially blocking a web container
thread
Example:- implementing SingleThreadModel interface
The configuration information contains initialization parameters (set of name/value pairs), the name of the
servlet, and a javax.servlet.ServletContext object, this gives the servlet information about the container. The
initialization parameters and the name of a servlet can be specified in the deployment descriptor (web.xml). For
example:
<web-app>
<servlet>
<servlet-name>Admin</servlet-name>
<servlet-class>com.wrox.admin.AdminServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:orcl</param-value>
</init-param>
</servlet>
</web-app>
method is specified in the Servlet Interface. Alternatively, servlets extending the GenericServlet, or its subclass
HttpServlet can also call the method of the ServletConfig interface directly. This is because the GenericServlet
also implements the ServletConfig Interface.
Example 6:-
servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.util.Enumeration;
Matrix Computers (Page 40 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
5. import javax.servlet.RequestDispatcher;
6. import javax.servlet.ServletContext;
7. import javax.servlet.ServletException;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11. public class Servlet1 extends HttpServlet
12. {
13. protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
14. {
15. ServletContext context = getServletContext();
16. PrintWriter out = response.getWriter();
17.
18. context.setAttribute("name", "Matrix Reloaded");
19. context.setAttribute("password", "computers");
20.
21. Enumeration en = context.getAttributeNames();
22. while (en.hasMoreElements())
23. {
24. out.print((String) en.nextElement());
25. out.print("<br>");
26. }
27. out.print("<br>");
28. context.removeAttribute("name");
29. out.print("Attribute having reference name is removed");
30.
31. out.print("<br>");
32. String user = context.getInitParameter("user");
33. out.print("Init param value for user is:" + user);
34. out.print("<br>");
35. Enumeration en1 = context.getInitParameterNames();
RIX
AT
M
60. out.print("<br>");
61.
62. String realpath = context.getRealPath("/WEB-INF/web.xml");
63. out.print("The Real Path of web.xml is:" + realpath);
64. out.print("<br>");
65.
66. RequestDispatcher rd = context.getRequestDispatcher("/servlet2");
67. // use forward(req,res) or include(req,res) with rd
68. context.log("You can see this log message in logs folder of TOmcat");
69. out.print("<br>");
70.
71. out.print("URL of web.xml is:-"+ context.getResource("WEB-INF/web.xml"));
72. }
73. }
web.xml
1. <web-app>
2. <display-name>servletContext APP</display-name>
3. <context-param>
4. <param-name>user</param-name>
5. <param-value>Matrix Research</param-value>
6. </context-param>
7. <context-param>
8. <param-name>location</param-name>
9. <param-value>Jaipur</param-value>
10. </context-param>
11. <servlet>
12. <servlet-name>servlet1</servlet-name>
13. <servlet-class>com.matrix.Servlet1</servlet-class>
14. </servlet>
15. <servlet-mapping>
16. <servlet-name>servlet1</servlet-name>
17. <url-pattern>/servlet1</url-pattern>
RIX
AT
M
18. </servlet-mapping>
19. </web-app>
Output:-
Matrix Computers (Page 42 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
RIX
A. javax.servlet.ServletException
Defines a general exception a servlet can throw when it encounters difficulty. The container sends the
HTPP-500 error to the client.
Constructors:-
• public ServletException ( )
Construct a new Servlet Exception
• public ServletException (String msg)
Constructs a new servlet exception with the specified message. The message can be written to the
server log and/or displayed for the user.
• public ServletException(String msg, Throwable rootcause)
Constructs a new servlet exception when the servlet needs to throw an exception and includes a
parameter corresponding to the “root cause” exception that interfered with its normal operation, and a
description message.
• public ServletException (Throwable rootcause)
Matrix Computers (Page 43 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Constructs a new servlet exception when the servlet needs to throw an exception and includes a
parameter corresponding to the “root cause” exception that interfered with its normal operation.
B. javax.servlet.UnavailableException
Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily
unavailable. A servlet or filter is temporarily unavailable if it cannot handle request momentarily due to some
system wide problem. For example, a third-tier server might not be accessible or there may be insufficient
memory or disk storage to handle requests . A system administrator may need to take corrective action.
A servlet or filter is permanently unavailable if during its execution an exception occurs which can not
be recovered. Servlet containers can safely treat both types of unavailable exceptions in the same way.
However, treating temporary unavailable effectively makes the servlet container more robust. Specifically, the
servlet container might block requests to the servlet or filter for a period of time suggested by the exception
rather than rejecting them until the servlet container restarts.
Constructors:-
• UnavailableException (String msg)
Constructs a new exception with a description message indicating that the servlet is permanently
unavailable. The container sends the HTTP-404 (permanent unavailable) error to the client.
• UnavailableException (String msg, int seconds)
Constructs a new exception with a descriptive message indicating that the servlet is temporarily
unavailable and giving an estimate of how long it will be unavailable. In some cases, the servlet cannot make
an estimate . For example, the servlet might know that a server it needs is not running but not be able to report
how long it will take to restore the functionality? This can be indicated with a -ve or zero value for the second
argument. The container sends the HTTP-503(Temporary Unavailable) error to the client.
HTTP-500 (for any other ServletException)
2. <head>
AT
M
17. }
18. public void init()throws ServletException
19. {
20. states.add(createState("Initialization"));
21. String waitIntervalString=getServletConfig().getInitParameter("waitInterval");
22. if (waitIntervalString!=null)
23. {
24. waitInterval=new Integer(waitIntervalString).intValue();
25. }
26. }
27. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
28. {
29. if(random.nextBoolean())
30. {
31. states.add(createState("Unavailable from doGet..."));
32. throw new UnavailableException("unavailable from doGet",waitInterval);
33. //not available for waitInterval seconds
34. //throw new UnavailableException("Unavailable from doGet")
35. //throw new ServletException("Unavailabe from doGet...")
36. }
37. states.add(createState("Service"));
38. response.setContentType("text/html");
39. PrintWriter out=response.getWriter();
40. //Send acknowledgment the browser
41. out.print("<html><head><title> LifeCycleServlet </title></head>");
42. out.print("<body>");
43. out.print("waitInterval:="+waitInterval);
44. out.print("<h1>LifeCycleSevlet: State Story</h1>");
45. out.print("<p><a href=\"life\"> Reload </a></p>");
46. for(int i=0;i<states.size();i++)
47. out.print("<p>"+ states.elementAt(i)+"</p>");
RIX
AT
M
48. out.print("</body></html>");
49. out.close();
50. }
51. public void destroy()
52. {
53. states.add(createState("Destroy"));
54. System.out.println("Flushing state history of LifeCycle servlet. ");
55. for(int i=0;i<states.size();i++)
56. System.out.println(states.elementAt(i).toString());
57. }
58. private String createState(String message)
59. {
60. return "[" +(new Date()).toString()+"]"+message;
61. }
62. }
web.xml
1. <web-app>
2. <display-name>Life Cycle Servlet</display-name>
3. <servlet>
4. <servlet-name>life</servlet-name>
5. <servlet-class>LifeCycleServlet</servlet-class>
6. <init-param>
7. <param-name>waitInterval</param-name>
8. <param-value>5</param-value>
Matrix Computers (Page 45 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
9. </init-param>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>life</servlet-name>
13. <url-pattern>/life</url-pattern>
14. </servlet-mapping>
15. <error-page>
16. <error-code>503</error-code>
17. <location>/error.html</location>
18. </error-page>
19. <error-page>
20. <error-code>500</error-code>
21. <location>/error1.html</location>
22. </error-page>
23. </web-app>
error.html
1. <html>
2. <meta http-equiv="pragma" content="no-cache">
3. <head>
4. <title> lifecycleservlet unavailable </title>
5. </head>
6. <body>
7. <h1>lifecycle servlet unavailable</h1>
8. <p>lifecycle servlet is temporarily unavailable(503)
9. click this <a href="http://localhost:8080\lifecycle\life">again</a></p>
10. </body>
11. </html>
error1.html
1. <html>
2. <meta http-equiv="pragma" content="no-cache">
3. <head>
4. <title> lifecycle servlet unavailable </title>
RIX
AT
M
5. </head>
6. <body>
7. <p>Any other lifecycle servlet Exception(500)</p>
8. </body>
9. </html>
Output:-
Matrix Computers (Page 46 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
RIX
AT
M
processing of a request is complete, the Servlet container sets the request object to default and uses the same object
for other requests. However, it does not use the same request objects to serve more than one request at a time.
Apart from request parameters, web containers or Servlet/JSPs can attach attributes to requests. The Servlet
API specification specifies three different approaches for storing and retrieving attributes:
• Attaching attributes to request objects
• Storing attributes in Http Session object
• Servlet context.
The JSP specification provides an additional mechanism using page context to store and retrieve attributes.
Each of these approaches provides the notion of a scope for the attributes to exit: In the case of attributes attached to
the request objects, the lifetime of these attributes is that of the request itself.
In the servlet, an attribute is a named Java language object. While setting an attribute, you assign a name to
the attribute, and while retrieving the attribute, specify the same name. Names are String objects. The purpose of
attributes in the request scope is to allow the container or another servlet to send additional data to a servlet or JSP.
For the application developers, this is useful when using the Request Dispatcher object to forward request from one
servlet to another. The following methods can be used to manage attributes in the request context
• public Enumeration getParameterNames():-This method returns an enumeration of all the parameter names
M
for the request. If the request has no parameters, it returns an empty enumeration.
• public String[] getParameterValues(String):- If a parameter can return multiple values, such as a set of
check boxes, a multi selection-list, or even multiple controls with the same name, this method returns an array
containing the parameter values.
• public Map getParameterMap():-This method returns a java.util.Map containing all request parameters. In
this map, the name of the parameter is the key while its value is the map value. Both keys and values are
strings. Note that this map is immutable and you cannot change the contents of this map.
• public String getProtocol():-Returns the name and version of the protocol when a request is made. For
example, if we make a request by using HTTP1.1, this method returns HTTP/1.1.
• public String getScheme():-Returns the name of the scheme used to handle this request, such as HTTP,
HTTPS or FTP.
• public String getServerName():- Returns the name of the server receiving the request.
• public int getServerPort():-Returns the port number on which the server is running and receives this request.
• public BufferedReader getReader() throws IOException:- This method can be used to access the body of
the request using a buffered reader object.
• public String getRemoteAddr():- Returns the IP address of the client.
• public String getRemoteHost():- Returns the fully qualified name of the client sending the request.
• public void setAttribute(String, Object):-Stores an attribute to a specific client request.
• public void removeAttribute(String):-Removes an attribute to a specific client request.
• public Object getAttribute(String):-Returns the value of the named attribute as an Object form, or returns
null if no attribute of the given name exists.
Matrix Computers (Page 48 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Methods:-
• public String getPathInfo ( ) :-This method returns any extra path information associated with the request
URL. In general, you invoke a servlet using its alias or the class name. For instance, you can access a servlet
MyServlet using URL http://host:port/myApp/MyServlet where myAPP is the application context. However, you
can send additional path information to the servlet say as http://host:port/myApp/MyServlet/matrix. In this case
/matrix is the additional path information returns null if there is no additional path in the request.
• public String getPathTranslated ( ) :-The method translates the extra path information into a real path. For
instance, if the directory corresponding
to myApp application is c:\tomcat5.5\eabapps\myApp\matrix as the translated path. This method returns null
if there is no additional path in the request.
• public String getQueryString():-The method returns the query String associated with the request.
• public String getRequest URI( ):-This method returns URI path associated with the request. In the above
example, this method would
return/myApp/MyServlet/devesh i.e. the path starting with the server root. The query string is excluded.
• public String getRequestURL ( ) :-This method reconstructs the URL that the client used to make this
request. The returned string included the
protocol, Server name, Port and the Server path for this request. The query string is excluded. For instance,
in the above example, this method would return http://host:port/myAPP/MyServlet/matrix .
• public String getServletPath( ) :-This method returns the URI path associated with this Servlet. This excludes
any extra Path information and
query string. For Instance, in the above example, this method would return /myApp/MyServlet as the servlet
path.
Matrix Computers (Page 49 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
• public String getHeader(String name):-The method returns the value of the named header from the HTTP
request. This method returns null if the request does not include the specified header. The header ”host”
returns the name of the machine sending the request. The header “user-agent” returns the browser information.
• public Enumeration getHeaderNames( ) :-This method returns an enumeration of names of request headers.
• public String getMethod ( ) :-This method returns the type of the HTTP request such as GET, POST and so
on.
• public void setBufferSize(int size):- Sets the preferred buffer size for the body of the respons
• public int getBufferSize( ) :- Returns the actual buffer size used for the response.
• public void resetBuffer( ):-This method clears content of the underlying buffer without clearing the response
headers or the status code. If the response has already been committed, then method throws an Illegal State
Exception.
• public void flushBuffer( ) :- Forces any content in the buffer to be written to the client.
• public boolean isCommitted( ) :- Returns a boolean indicating if the response has been committed.
• public void reset ( ) :-This method clears content of the underlying buffer as well as the response headers.
• public void sendRedirect (String location):-This method sends a redirect response to the client. The client
receives the HTTP response code 302 indicating that temporarily the client is being redirected to the specified
location. If the specified location is relative, this method converts it into an absolute URL before redirecting.
6. Servlet Collaboration:-
In the typical servlet model, a servlet received an HTTP request, executes some application logic, and prepares
the response. This completes one request – response trip for the client. However, there are several scenarios in which
the basic model is not adequate:
1. A Servlet receives an HTTP request from a client, processes application logic, and a JSP drives the
response. In this case the servlet is not responsible for response generation. instead, the JSP page is responsible for
the dynamic content.
2. A Servlet receives an HTTP request from the client, processes application logic, partially and hands over
the request to another servlet. The second servlet completes the application logic and either prepares the response or
requests a JSP page to drive the response.
In both the scenarios, the servlet is not completely responsible for processing a request. Instead it delegates
the processing to another servlet (or JSP page, which is equivalent to a servlet at run time).
RIX
AT
M
Request Dispatching:-
Request dispatching allows a servlet or a JSP Page to dispatch a request to another servlet ( or a JSP, or even
a plain HTML page) which will then be responsible for any further processing and for generating the response. when
the web container receives a request, it constructs request and response objects and invokes one of the servlet’s
services methods with the request and response objects. This is a process of the web container dispatching a request
to a servlet. What if the servlet wants to dispatch the same request to another servlet after preliminary processing?
For this purpose, the first servlet should be able to obtain a reference to the second servlet. Using this reference
the first servlet can dispatch the request to the second servlet. in simple terms this is the request dispatching. The java
Servlet API has a special interface called javax.servlet.RequestDispatcher for this purpose.
begin with ’/’ otherwise it throws IllegalArgumentException). For example if you have a
servlet/mywebApp/servlet1, and want to get the requestDispatcher object for /mywebApp/servlet2, you should
specify the complete path relative to the root context. Here the root context is /mywebApp, and the absolute
path is /servlet2. The same method on servletRequest accepts both absolute and relative paths. In the above
example, you could now also use servlet2 as the path. If these methods locate a resource, it creates a
RequestDispatcher object that wraps the resource and returns the resultant object. If the resource cannot be
located by using the path, it creates a RequestDispatcher object to add the message “The requested resource
(<path>) is not available” in the output, and returns the resultant object.
The getNameDispatcher() method on the servlet context is a convenience method that accepts a name
associated with servlet. This is the same name that you specify in the deployment descriptor (web.xml) in the
<servlet-name> element. Note that the target object (except for static resources) should implement the same
type of Http request that the original servlet receives.
Methods in RequestDispacher:-
• public void forward(ServletRequest request, ServletResponse response)
Forwards the servlet's request object to another static or dynamic resource. Including Other Resources in the
Response. It is often useful to include another web resource (html, jsp, servlet, image) in the response returned
from a web component. To include another resource, invoke the include method of a RequestDispatcher
object: If the included resource is static, the include method enables programmatic server-side includes. If the
resource is a web component, the include() method sends the request to the included web component, then
Container executes the web component, and then include the result of the execution in the response from the
calling servlet. An included web component has access to the request object, but it is limited to access
response object: It can write to the body of the response and commit a response. It cannot set headers or call
any method (for example, setCookie) that affects the headers of the response.
RIX
AT
M
With both the include and forward methods the control comes back to the source Servlet only after the target
Servlet’s service method execution has been completed. However in the case of the forward method, before the control
comes to the source Servlet, the response is already committed and ended (that is, we cannot add any more content
into the response).
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class ServletOne extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. out.print("<h2>This is Servlet One <br> </h2>");
14. RequestDispatcher rd=request.getRequestDispatcher("/servlettwo");
15. rd.forward(request, response);
16. out.close();
17. }
18. }
ServletTwo.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.RequestDispatcher;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
Matrix Computers (Page 55 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
7. import javax.servlet.http.HttpServletResponse;
8. public class ServletTwo extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. out.print("<h2>This is Servlet Two</h2>");
14. out.print("<br>");
15. RequestDispatcher rd= request.getRequestDispatcher("/servletthree");
16. rd.include(request, response);
17. out.print("<h4>This is because of Request Disapatcher's include and forward
methods</h4><br> ");
18. out.print("<h4>ServletOne forwards request to servletTwo and ServletTwo includes output of
ServletThree</h4>");
19. }
20. }
ServletThree.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.HttpServlet;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. public class ServletThree extends HttpServlet
8. {
9. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
10. {
11. PrintWriter out=response.getWriter();
12. out.print("<h2> and <br> <br>This is Servlet Three</h2>");
13. }
RIX
AT
M
14. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>sone</servlet-name>
4. <servlet-class>ServletOne</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>sone</servlet-name>
8. <url-pattern>/servletone</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>stwo</servlet-name>
12. <servlet-class>ServletTwo</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>stwo</servlet-name>
16. <url-pattern>/servlettwo</url-pattern>
17. </servlet-mapping>
18. <servlet>
19. <servlet-name>sthree</servlet-name>
20. <servlet-class>ServletThree</servlet-class>
21. </servlet>
22. <servlet-mapping>
Matrix Computers (Page 56 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
23. <servlet-name>sthree</servlet-name>
24. <url-pattern>/servletthree</url-pattern>
25. </servlet-mapping>
26. </web-app>
Output:-
RIX
AT
M
ValidationServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import java.io.*;
Matrix Computers (Page 57 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
9. int op2=((Integer)req.getAttribute("operand2")).intValue();
10. int result=op1-op2;
11. req.setAttribute("operation", "Subtraction");
12. req.setAttribute("result", new Integer(result));
13. RequestDispatcher rd=req.getRequestDispatcher("/resp");
14. rd.forward(req,res);
15. }//service
16. }//class
ResponseServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import java.io.*;
4. public class ResponseServlet extends GenericServlet
5. {
6. public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException
7. {
8. Integer result=(Integer) req.getAttribute("result");
9. RequestDispatcher rd=req.getRequestDispatcher("/index.html");
10. if (result==null)
11. {
12. rd.forward(req,res);
13. return;
14. /*return is required here since we know that after forward the control comes back
15. to the source servlet, and here we dont want to execute the remaning part
16. of this service if our request is forwarded */
17. }//if
18. res.setContentType("text/html");
19. PrintWriter out=res.getWriter();
20. String op=(String) req.getAttribute("operation");
21. out.println(op+" Result : <b>"+result.intValue()+"</b><br/>");
22. rd.include(req,res);
RIX
AT
M
23. }//service
24. }//class
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>es</servlet-name>
4. <servlet-class>com.matrix.ValidationServlet</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>as</servlet-name>
8. <servlet-class>com.matrix.AddServlet</servlet-class>
9. </servlet>
10. <servlet>
11. <servlet-name>ss</servlet-name>
12. <servlet-class>com.matrix.SubServlet</servlet-class>
13. </servlet>
14. <servlet>
15. <servlet-name>rs</servlet-name>
16. <servlet-class>com.matrix.ResponseServlet</servlet-class>
17. </servlet>
18. <servlet-mapping>
19. <servlet-name>es</servlet-name>
20. <url-pattern>/entry</url-pattern>
21. </servlet-mapping>
Matrix Computers (Page 59 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
22. <servlet-mapping>
23. <servlet-name>as</servlet-name>
24. <url-pattern>/add</url-pattern>
25. </servlet-mapping>
26. <servlet-mapping>
27. <servlet-name>ss</servlet-name>
28. <url-pattern>/sub</url-pattern>
29. </servlet-mapping>
30. <servlet-mapping>
31. <servlet-name>rs</servlet-name>
32. <url-pattern>/resp</url-pattern>
33. </servlet-mapping>
34. </web-app>
7. Session Management:
A servlet receives a request object, extracts parameters (if any) from it, processes any application logic (which
may depend on the request parameters), and finally generates the purpose. Extending this model, you could build
larger web applications by having several servlets, with each servlet performing a well-defined independent task.
The model is adequate so long as the application logic in each of these servlets is atomic-that is, so long as
the application logic depends only on the parameters in the request (and, if applicable, any persistent data such as
data stores in a relational database). For instance, in the Request Response application the servlet gets all the request
data from the request (from text fields), and displays in browser. We can also process these data.
shopping cart.
This is a typical requirement for web application where a ‘user activity’ happens across multiple requests and
responses, and the server is required to associate some form of uniqueness to each of the users.
For implementing flexible business transaction across multiple requests and responses, we need two facilities.
Matrix Computers (Page 60 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
• Session:The server should be able to identify that a series of requests are from a single client and responses,
we need single working session.
• State:The server should be able to remember information related to previous requests and other business
decisions that are made for requests. That is, the application should be able to associate state with each
session. In the case of the shopping cart application, possible state could include the user’s favorite item
categories, user profile, or even the shopping cart itself.
This simple technique of session tracking can be adopted in different ways, based on how such a token can
RIX
AT
M
be represented and exchanged. The tokens are exchanged in the above four approaches as described below:
URL Rewriting:-
URL rewriting implies adding session data to the URL path, which is then interpreted by the web container to
associate the request with a session. In URL rewriting , the session data required in the next request is appended to
the URL path. The required session data is retrieved by the web server as request parameters.
In other words: The token or identifier(session data) is embedded in each URL. In each dynamically generated
page, the server embeds an extra query parameter or extra path information, in each URL in the page. When the client
submits requests using such URLs, the token is retransmitted to the server. This approach is called URL rewriting, as
it involves rewriting URLs in the response content to embed the extra token.
Suppose a URL is like action=”servlet1” and now you want to pass username along with this URL then Rewrite
this URL like action=”servlet1?username=matrix”. URL rewriting requires that all pages in application be dynamically
generated. URL rewriting cannot be enforced for static HTML pages, because the unique URL path parameter is
dynamic and differs from user to user.
We can rewrite a URL in anchors also like <a href=”servlet1?username=matrix”>Call Servlet1</a>
Example:-In this example we are inserting username and password in index.html and sending request to Servlet1.
Servlet1 reads the username and password and generates output. Now a form generated by Servlet1’s rewritten URL
having username and password as query string is submitted to Servlet2. Servlet2 reads the rewritten URL information
using getParameter() method.
Example 11:-
index.html
Matrix Computers (Page 61 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
1. <html>
2. <body>
3. <form method=post action=servlet1>
4. Username<input type=text name=username value=""><br>
5. Password<input type=password name=password value=""><br>
6. <input type=submit value=Login>
7. </form>
8. </body>
9. </html>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. out.print("Welcome : ");
16. out.print(username);
17. out.print("<form method=post action=servlet2?username="+username+"&
password="+password+">");
18. out.print("<input type=text name=email value=''>");
19. out.print("<input type=submit value=Submit>");
20. out.print("</form>");
RIX
AT
M
21. }
22. }
Servlet2.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet2 extends HttpServlet
9. {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. String user=request.getQueryString ();
16. out.print(user);
17. String email=request.getParameter("email");
18. out.print("Welcome : ");
19. out.print(username);
20. out.print("<br>Password inserted in index.html is :");
Matrix Computers (Page 62 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
21. out.print(password);
22. out.print("<br>E-mail is : ");
23. out.print(email);
24. }
25. }
Note:- 1. If you are using URL rewriting in a form then use method=post otherwise the URL will not work properly.
2. Don’t give any space anywhere in URL like: action=servlet2? username= “user1”& password=”matrix”.
Example 12:-
index.html
1. <form method=post action=servlet1>
2. Username<input type=text name=username value=""><br>
3. Password<input type=password name=password value=""><br>
4. <input type=submit value=Login>
5. </form>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
RIX
AT
M
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet2 extends HttpServlet
9. {
10. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. PrintWriter out=response.getWriter();
13. String username=request.getParameter("username");
14. String password=request.getParameter("password");
15. String email=request.getParameter("email");
16. out.print("Welcome : ");
17. out.print(username);
18. out.print("<br>Password inserted in index.html is :");
19. out.print(password);
20. out.print("<br>E-mail is : ");
21. out.print(email);
22. }
23. }
Above program have one index.html for login purpose and username and password is entered by User. The
form inside index.html is submitting to Servlet1. Servlet1 is reads username and password and generates an another
form. In Servlet1’s form we are setting username and password as hidden fields and form submits to Servlet2. Now
Servlet2 is able to read the hidden fields.(username and password we given in index.html).
Cookies:-
Cookies were invented by Netscape, and are one of the most refined forms of token that clients and servers
RIX
AT
M
can exchange. Unlike URL rewriting or using hidden form fields, cookies can be exchanged in request and response
headers, and therefore do not involve manipulating the generated response to contain a token.
Cookies are most commonly used means of tracking client sessions.
Definition: A Cookies is a small piece of textual information sent be the server to the client, stored on the client, and
returned by the client for all request to the server.
A Cookie contains one or more name- value pairs with certain additional attributes, which are exchanged in
the response and request headers. Web servers send a cookie by sending the set-Cookie response header.
The container can transparently set Cookies in the response headers, and extract Cookies from request
headers.
The Servlet API specification requires that the web containers implement session tracking using the cookie
mechanism. In this approach, the web container automatically sets a session tracking cookie with name jsessionid.
When the container receives client requests it checks for existence of this Cookie, and accordingly tracks sessions.
However, since servers can transparently set cookies, which are stored in the user’s computer and sent back to the
server, Cookies cause security concerns for many users. In order to answer for such concerns, browser allows you to
disable cookies. When Cookies are disabled, Servlet Containers use URL rewriting to track sessions.
Note: Although several sites require Cookies and provide limited or no functionality when Cookies are disabled,
it is a good practice to design web applications to support URL rewriting. Apart from Session Tracking Cookies, your
web application can explicitly set cookies in the response. Using the servlet API, you can add several Cookies in the
response and extract Cookies from request.
Example:-
Creating a Cookie and sending it to the browser so that it can be stored on the Client m/c.
Cookie c=new Cookie(“uid”,“dev”);
c.setMaxAge(60*60);
c.setDomain(“www.myserver.com”); //cookies will be sent back to the domain
c.setPath(“/”);// cookies will be sent for any URL for the above domain
response.addCookie(c);// cookie is added to the response header
Similarly you can retrieve cookies from requests using getCookies() method on the HTTPServletRequest
interface. Possible application for setting explicit Cookies include targeted marketing, site personalization, usage
tracking etc.
Cookies c[ ]=request.getCookies();
RIX
AT
M
We can iterate the array and retrieve the cookie name and value using getName() and getValue() methods.
AddCookieServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.Cookie;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import javax.servlet.http.HttpServlet;
8. public class AddCookieServlet extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. String data=request.getParameter("data");
13. Cookie cookie=new Cookie("MyCookie",data);
14. response.addCookie(cookie);
15. response.setContentType("text/html");
16. PrintWriter out=response.getWriter();
17. out.print("<html>");
18. out.print("<head><title>Adding Cookies</title></head>");
19. out.print("<body>");
20. out.print("<h3>MyCookie has been set to response");
21. out.print("<br>Cookie value is \t");
22. out.print(data);
23. out.print("</h3><br>");
24. out.print("<a href='getcookie.html'>Click here to go next</a>");
25. out.print("</body>");
26. out.print("</html>");
27. out.close();
28. }
29. }
GetCookieServlet.java
RIX
AT
M
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.Cookie;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import javax.servlet.http.HttpServlet;
8. public class GetCookieServlet extends HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. Cookie cookie[]=request.getCookies();
13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15. out.print("<html>");
16. out.print("<head><title>Getting Cookies</title></head>");
17. out.print("<body>");
18. out.print("<b>");
19. for(int i=0;i<cookie.length;i++)
20. {
21. String name=cookie[i].getName();
22. String value=cookie[i].getValue();
23. out.print("Name: "+name+" value: "+value);
Matrix Computers (Page 66 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
24. }
25. out.print("</body>");
26. out.print("</html>");
27. out.close();
28. }
29. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>AddCookieServlet</servlet-name>
4. <servlet-class>AddCookieServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>AddCookieServlet</servlet-name>
8. <url-pattern>/addcookie</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>GetCookieServlet</servlet-name>
12. <servlet-class>GetCookieServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>GetCookieServlet</servlet-name>
16. <url-pattern>/getcookie</url-pattern>
17. </servlet-mapping>
18. </web-app>
Output:-
RIX
AT
M
Matrix Computers (Page 67 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
sessions. The servlet specification allows web containers to use URL rewriting, cookies, or SSL sessions for session
tracking. The actual technique used for establishing and tracking a given session depends on both the server’s and
clients capabilities to participate in sessions.
The server API also provides you with an interface, object of which let you manipulate session lifecycle, and
associate state with sessions. There are certain guidelines that make sure that session tracking is functional
irrespective of the technique used.
• void setMaxTimeInterval(int interval):-// in seconds Specifies the time, in seconds, between client requests
before the servlet container will invalidate this session.
• void invalidate():-Invalidates this session then unbinds any objects bound to it.
• boolean isNew():-Returns true if the client does not yet know about the session or if the client chooses not to
join the session.
1. <html>
2. <head>
3. <title>Session Tracking</title>
4. </head>
5. <body>
6. <center> <h3>For Session Management<a href="sessionmm">Click here</a></h3></center>
7. </body>
8. </html>
SessionManagement.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import java.util.Date;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import javax.servlet.http.HttpSession;
8. public class SessionManagement extends javax.servlet.http.HttpServlet
9. {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. String action=request.getParameter("action");
13. if(action!=null && action.equals("invalidate"))
14. {
15. //invalidate the session
16. HttpSession session=request.getSession();
17. session.invalidate();
18. response.setContentType("text/html");
19. PrintWriter out=response.getWriter();
20. out.print("<html>");
21. out.print("<head><title>Session Management</title></head>");
22. out.print("<body bgcolor=#99FF66>");
RIX
AT
M
47. }
48. out.print("<br><Session ID");
49. out.print(session.getId());
50. out.print("<br> Creation Time");
51. out.print(new Date(session.getCreationTime()));
52. out.print("<br>Last Accessed Time:");
53. out.print(new Date(session.getLastAccessedTime()));
54. out.print("<br>Maximum Inactive Interval in Seconds");
55. out.print(session.getMaxInactiveInterval());
56. String sessionURL=response.encodeURL("sessionmm");
57. out.print("<br><a href=\""+sessionURL+"?action=invalidate\">");
58. out.print("Invalidate the session</a>");
59. out.print("<br><a href=\""+sessionURL+"\"");
60. out.print("Reload This Page</a>");
61. out.print("</body></html>");
62. }
63. }
64. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>SessionManagement</servlet-name>
4. <servlet-class>SessionManagement</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>SessionManagement</servlet-name>
8. <url-pattern>/sessionmm</url-pattern>
9. </servlet-mapping>
10. <session-config>
11. <session-timeout>5</session-timeout>
12. </session-config>
13. </web-app>
RIX
AT
M
Output:-
Matrix Computers (Page 71 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
RIX
AT
M
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. import javax.servlet.http.HttpSession;
9. public class Servlet2 extends HttpServlet
10. {
11. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
12. {
13. HttpSession session=request.getSession();
14. String value=(String)session.getAttribute("key");
15. PrintWriter out=response.getWriter();
16. out.print("The Attributes value is:");
17. out.print(value);
18. out.print("<br>");
19. session.removeAttribute("key");
20. out.print("<br>");
21. out.print("Attribute Removed");
22. }
23. }
Attribute is available until your session in which you added your attribute is available. If you started a new
session suppose opened a new browser and retrieving the attribute then the attribute is not available because new
browser doesn’t have previous session.
Note1:-if you are setting attribute in context object then the attribute is available in whole application. If setting in
request then attribute is available until same request is available. If setting is session then the attribute is available till
session is alive.
Note2:-If you don’t know Attribute Name(key) then use following method.
RIX
AT
M
for context
Enumeration en=context.getAttributeNames();
for request
Enumeration en=request.getAttributeNames();
for session
Enumeration en=session.getAttributeNames();
getAttributeNames() method returns the names(keys) of added attributes in Enumeration. Retrieve keys and
then do operations on attributes like remove or get attributes.
process Enumeration:-
while(en.hasMoreElements())
{
en.nextElement();// this returns attribute’s names(keys).
}
Get Parameters:-
If you don’t know want to get parameters through their name then use getParameterNames() method. This
method returns an Enumeration having names of all the parameters coming through request. Now use Enumeration
to get the parameter names and values according names.
If there are more then one value in a parameter then use getParameterValues(“”) method. This method
returns array of values in form of String. The getParameter() method will give only one value.
See the following example you will find a checkbox having multiple values.
Matrix Computers (Page 73 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
Example 16:-
index.html
1. <html>
2. <head>
3. <title>index</title>
4. </head>
5. <body>
6. <center>
7. <form action=register method=post>
8. Name<input type=text name=username value="" maxlength=30><br>
9. FName<input type=text name=fname value="" maxlength=30><br>
10. Email<input type=text name=email value="" maxlength="40"><br>
11. Gender<input type=radio name=gender value=male>
12. Male<input type=radio name=gender value=female>Female<br>
13. Subject:
14. C<input type=checkbox name=subject value="C">
15. C++<input type=checkbox name=subject value="C++">
16. Java<input type=checkbox name=subject value="Java">
17. VB<input type=checkbox name=subject value="VB"><br><br>
18. <input type=submit name="submit" value="Submit">
19. </form>
20. </center>
21. </body>
22. </html>
RegisterServlet:-
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import java.util.Enumeration;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
RIX
AT
M
8. import javax.servlet.http.HttpServletResponse;
9. public class RegisterServlet extends HttpServlet
10. {
11. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
12. {
13. PrintWriter out = response.getWriter();
14. Enumeration en = request.getParameterNames();
15. while (en.hasMoreElements())
16. {
17. String name = (String) en.nextElement();
18. String value = request.getParameter(name);
19. out.print(value);
20. out.print("<br>");
21. }
22. String subject[] = request.getParameterValues("subject");
23. for (int i = 0; i < subject.length; i++)
24. {
25. out.print(subject[i] + "<br>");
26. }
27. }
28. }
Matrix Computers (Page 74 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
8. Implementing Filters:-
Filters are the most recent addition to the java servlet technology. The servlet specification version 2.3
introduced filters as a flexible means of interacting with HTTP requests and responses before and after the web-
container invoke wed resources including servlets.
For instance, consider the basic need to monitor requests to a specific kind of static file (such as certain type
of images or documents) on the container, and log the requests to a specific database. In order to build this functionality,
what you need is a facility to plug in some logic during the HTTP request handling process.
Why are filters special? As of J2EE 1.3 filters provide the only mechanism by which we can plug in code to
participate in the container interception process. Although filters are limited to the web container (that is we can filter
HTTP requests, but we can’t filter request to EJBs, and so on), we can perform several useful tasks with the help of
the filter in the web container to invoke certain filter objects during the HTTP request-response process. In this manner
as web application developers, we can customize how HTTP requests are handled within a wed container.
What Is A Filter?
A filter is a servlet like container-managed object that can be declaratively inserted within the HTTP request-
response process.
Like a servlet, a filter object is instantiated and managed by the container and follows a lifecycle that is similar
to that of a servlet. A filter has four stages: instantiate, initialize, filter and destroy. These stages are similar to a servlet’
s instantiate, initialize, service and destroy.
Filters also follow a deployment process close to that of servlets. In fact, the API of a filter is very similar to
that of the servlet’s Servlet interface a filter also operates on HTTP requests to produce and manipulate further HTTP
requests and responses. So how is a filter different from a servlet?
In order to see the difference, let us consider how filters participate in the HTTP request –response process.
RIX
AT
M
In this figure, there is a chain of two filters participating in the response process. Each filter (from left to right)
can manipulate the request and response or implement some logic (including updating the HTTP session or the servlet
context) and request the HTTP container to invoke the next filter (if any) in the filter chain. Ultimately after invoking the
last filter, the container processes the actual web resource.
Alternatively, any filter in this chain can choose to abort the processing and report an error in the HTTP
response. The arrows between the filter and between the second filter and the web resources are the servlet request
and servlet response objects.
In this process, after each filter is processed the control is transferred to the following filter in the chain. Similarly
after the web resource has been processed, the container returns the thread of execution back to the last filter. This
step continues till the control is handed back to the first filter. In this manner, each filter gets an opportunity to participate
both before and after invoking the web resources.
Use of Filter:-
1. Validation of Http Request:- Each filter has access to the http request object and therefore can validate the
contents of HTTP requests. If a request is invalid (that is, it contains invalid parameters, required parameters are
missing, or values of the supplied parameters are invalid), the filter can abort processing and report HTTP errors
to the container. In this way, we can avoid implementing any validation logic within servlet or jsp pages. We can
also extend this idea to preprocess HTTP request parameters.
2. Logging HTTP Requests:- Based on the contents of HTTP requests, we can implement custom access
logging for all web resourses. Typically, logging is the work of the web server and it usually control how logging is
Matrix Computers (Page 75 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
done. Filters give us a handle to implement our own logging (in addition to that of server). With filter we can request
application specific logging. For instance, we can build logging based on specific business events –filters let us
scan requests to determine the events.
3. Authorization of HTTP Requests:- Authorization is the process of checking if the client can access a given
resource. Typically, web applications implement custom authorization code in every servlet and jsp page. Instead
we can implement custom authorization within a filter and include the filter for all HTTP requests. We can also rely
on web-container managed declarative authorization.
4. Customizing HTTP environment for servlet and JSP pages:- We can also use the filter mechanism to
modify the request and response objects (and thereby the HTTP session as well). For instance, we can add
additional data to the request object, or fill in missing default parameters. We can also replace the request and
response objects to provide additional behavior.
Note: All these tasks could also be performed within a servlet, although with some difficulty.
Filter API:-
The Filter API consists of the following interfaces and classes:
• javax.servlet.Filter
The interface that all filters must implement.
• javax.servlet.FilterConfig
An interface that provides access to filter initialization parameters and the servlet context. This interface is created
by the container and passed on to the filter instance during initialization.
• javax.servlet.FilterChain
An abstraction of a filter chain. This interface lets you invoke the next filter in the chain, or if the calling filter is the
last filter in the chain, the resource at the end of the chain.
All these methods are container-invoked methods used during filter lifecycle. The lifecycle of a filter consists
of the following steps.
1. Instantiation:-An container startup or sometime before a filter instance is required before invocation. For each web
application, the container maintains one instance per filter.
2. Initialization:-After instantiating the container calls init() method. During the call, the container passes on
initialization parameters to the filter instance.
3. Invoke Filter:-After init() method doFilter() method is invoked.
4. Destroy:-This method will be called at the last.
Both init() and destroy() methods can throw ServletException while the doFilter() method can also throw
IOException. When these methods throw a ServletException, the container cannot continue with the filter chain which
means that it cannot serve the web resouces to which the request maps. Therefore, in cases where you want the
Matrix Computers (Page 76 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
container to serve the resource irrespective of any exceptions, it is important to make sure that the filters consume
exceptions and log those cases appropriately.
Methods:-
• public String getFilterName():-Returns the filter-name of this filter as defined in the deployment descriptor.
• public String getInitParameter(String name):- Returns a String containing the value of the named
initialization parameter, or null if the parameter does not exist.
• public Enumeration getInitParameterNames():- Returns the names of the filter's initialization parameters as
an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters.
• publicServletContext getServletContext():-Returns a reference to the ServletContext in which the caller is
executing.
TheFilterChain Interface:-
• public interface javax.servlet.FilterChain
Interface provides the filter with a handle to invoke the rest of the filter chain or next resource. Each filter access
to a FilterChain object when its doFilter() method is invoked.
Methods:-
• public void doFilter(ServletRequest request, ServletResponse response)
When a filter invokes this method, the container invokes the next filter in the chain. If the invoking filter is the
last filter in the chain, the container invokes the requested web resource.
What if a filter does not want further processing? In this case the filter can simply not call the doFilter() method
on the FilterChain object. But why should a filter not want to continue with the chain? Consider, for instance a filter that
validates the incoming request. If the filter finds that the request is incomplete, invalid, or inappropriate, it may choose
to abort the chain. In this case, the filter itself can write appropriate content back to the response.
RIX
AT
M
</filter>
<filter-mapping>
<filter-name>myfilter</filter>
<servlet-name>login</servlet-name>// this filter is assigned to servlet having name
//loginservlet
</filter-mapping>
…
…
….
</web-app>
9. </filter-mapping>
10. <servlet>
11. <servlet-name>myservlet</servlet-name>
12. <servlet-class>MyServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>myservlet</servlet-name>
16. <url-pattern>/demofilter</url-pattern>
17. </servlet-mapping>
18. </web-app>
Note :- To call filters of second servlet which is called by request dispatcher we have to add a line in <servlet-mapping>
tag <dispatcher>INCLUDE</dispatcher>
Output:-
Matrix Computers (Page 79 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
RIX
AT
M
Note:- Filter’s execution is divided into two parts, one is before chain.doFilter(Request, Response) method and one
is after chain.doFilter(Request, Response) method. First one called request execution and second one is called
response execution.
Listeners:-
RIX
A servlet can be designed as an event listener. This enables the servlet to be notified when some external
AT
M
event or changes occurred. There are a number of listener interfaces that you can implement for your servlet. All the
listener interface extends java.util.EventListener. Create a class by implementing corresponding interface to listen
particular event in your web application. For example: The listener classes for httpsession events are often used as a
way of tracking sessions within a Web application. for example, it is often useful to know whether a session became
invalid because the Web server timed out the session or because a Web Component within the application called the
invalidate() method.
Register your listener class in web.xml by using <listener> tag, child tag of <web-app>
<web-app>
<listener>
<listener-class>com.matrix.MyListener</listener-class>
</listener>
-------------
-------------
</web-app>
At the application level, the javax.servlet package provides two listener interfaces that support event
notifications for state changes in the ServletContext object.
1. ServletContextListener interface
2. ServletContextAttributeListener interface.
Methods:-
• public void contextInitialized(ServletContextEvent sce) :- The contextInitialized method is called when the
web application is ready to service requests. The method is called automatically by the servlet container when
its own initialization process is finished.
• public void contextDestroyed(ServletContextEvent sce):-The contextDestroyed method is invoked when
the servlet context is about to be shut down. You can use this method to write code that needs to run when
the application shuts down, such as closing a database connection or writing to the log.
Deployment Descriptor
Register listener class in web.xml. The <web-app> element must contain a <listener> element.
<web-app>
<listener>
<listener-class>AppLifeCycleEvent</listener-class>
</listener>
</web-app>
The <listener> element must come before the <servlet> part.
If you want, you can have more than one listener class. To do this, list all the listener classes in the deployment
descriptor, as follows:
<web-app>
<listener>
RIX
AT
<listener-class>AppLifeCycleEvent1</listener-class>
M
</listener>
<listener>
<listener-class>AppLifeCycleEvent2</listener-class>
</listener>
</web-app>
With a deployment descriptor like this, when Tomcat starts, it will call the contextInitialized method in the
AppLifeCycleEvent1 class and then call the same method in the AppLifeCycleEvent2 class.
Listening to ServletContextAttributeListener:-
In addition to a life cycle listener, you also can implement the ServletContextAttributeListener interface to be
notified when any attribute is added to the ServletContext or if any of the ServletContext's attributes are changed or
removed.
public interface ServletContextAttributeListener extends EventListener
ServletContextAttributeEvent class:-
• String getName():-Return the name of the attribute that changed on the ServletContext.
• Object getValue():-Returns the value of the attribute that has been added, removed, or replaced.
Example 18:-
index.html
1. <html><body>
2. <a href="s1">Click here to Listen Context</a>
3. </body>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import javax.servlet.ServletContext;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException
11. {
12. ServletContext ctx=getServletContext();
13. ctx.setAttribute("application", "Context Attribute");
14. ctx.setAttribute("application", "Context Attribute Replaced");
15. ctx.getAttribute("application");
16. ctx.removeAttribute("application");
17. }
18. }
Context11.java
1. package com.matrix;
RIX
AT
M
2. import javax.servlet.ServletContextEvent;
3. import javax.servlet.ServletContextListener;
4. public class Context11 implements ServletContextListener
5. {
6. public void contextInitialized(ServletContextEvent sce)
7. {
8. System.out.println("context initialized");
9. }
10. public void contextDestroyed(ServletContextEvent sce)
11. {
12. System.out.println("Context Destroyed");
13. }
14. }
Attribute11.java
1. package com.matrix;
2. import javax.servlet.ServletContextAttributeEvent;
3. import javax.servlet.ServletContextAttributeListener;
4. public class Attribute11 implements ServletContextAttributeListener
5. {
6. public void attributeAdded(ServletContextAttributeEvent scae)
7. {
8. String name=scae.getName();
9. String value=(String)scae.getValue();
10. System.out.println("Attribute "+name+ " added and The Value is: "+value);
Matrix Computers (Page 83 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
11. }
12. public void attributeRemoved(ServletContextAttributeEvent scae)
13. {
14. String name=scae.getName();
15. System.out.println("Attribute "+name+" Removed");
16. }
17. public void attributeReplaced(ServletContextAttributeEvent scae)
18. {
19. String name=scae.getName();
20. System.out.println("Attribute "+ name+" Replaced.");
21. }
22. }
web.xml
1. <web-app>
2. <listener>
3. <listener-class>com.matrix.Context11</listener-class>
4. </listener>
5. <listener>
6. <listener-class>com.matrix.Attribute11</listener-class>
7. </listener>
8. <servlet>
9. <servlet-name>s1</servlet-name>
10. <servlet-class>com.matrix.Servlet1</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>s1</servlet-name>
14. <url-pattern>/s1</url-pattern>
15. </servlet-mapping>
16. </web-app>
HttpSessionListener and HttpSessionAttributeListener. The first enables you to listen to a session's life cycle events,
that is, the event that gets triggered when an HttpSession object is created and the event that is raised when an
HttpSession object is destroyed. The second interface, HttpSessionAttributeListener, provides events that get raised
when an attribute is added to, removed from, or modified in the HttpSession object.
The two interfaces are explained next.
Example 19 HttpSessionEvent:-
index.html
1. <html>
2. <head>
3. <title>User Counter</title>
4. </head>
5. <body>
6. <a href=usercounter>Click</a>
7. </body>
8. </html>
The SessionLifeCycleEventDemo Class
1. package com.matrix;
2. import javax.servlet.http.HttpSession;
3. import javax.servlet.http.HttpSessionListener;
4. import javax.servlet.http.HttpSessionEvent;
5. import javax.servlet.ServletContextListener;
6. import javax.servlet.ServletContext;
7. import javax.servlet.ServletContextEvent;
8. public class SessionLifeCycleEventDemo implements ServletContextListener, HttpSessionListener
9. {
10. ServletContext context;
11. int counter;
12. public void contextInitialized(ServletContextEvent sce)
13. {
14. context = sce.getServletContext();
15. context.setAttribute(("userCounter"), Integer.toString(counter));
16. }
17. public void contextDestroyed(ServletContextEvent sce)
18. {
19. }
20. public void sessionCreated(HttpSessionEvent hse)
RIX
AT
M
21. {
22. System.out.println("Session created.");
23. incrementUserCounter();
24. }
25. public void sessionDestroyed(HttpSessionEvent hse)
26. {
27. System.out.println("Session destroyed.");
28. decrementUserCounter();
29. }
30. synchronized void incrementUserCounter()
31. {
32. counter = Integer.parseInt((String)context.getAttribute("userCounter"));
33. counter++;
34. context.setAttribute(("userCounter"), Integer.toString(counter));
35. System.out.println("User Count: " + counter);
36. }
37. synchronized void decrementUserCounter()
38. {
39. int counter = Integer.parseInt((String)context.getAttribute("userCounter"));
40. counter--;
41. context.setAttribute(("userCounter"), Integer.toString(counter));
42. System.out.println("User Count: " + counter);
43. }
44. }
Matrix Computers (Page 85 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
UserCounterServlet.java
1. package com.matrix;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. import java.io.*;
5. public class UserCounterServlet extends HttpServlet
6. {
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
8. {
9. ServletContext context = getServletContext();
10. HttpSession session = request.getSession(true);
11. int userCounter = 0;
12. userCounter = Integer.parseInt((String)context.getAttribute("userCounter"));
13. response.setContentType("text/html");
14. PrintWriter out = response.getWriter();
15. out.println("<HTML>");
16. out.println("<HEAD>");
17. out.println("<TITLE>User Counter</TITLE>");
18. out.println("</HEAD>");
19. out.println("<BODY>");
20. out.println("There are " + userCounter + " users.");
21. out.println("</BODY>");
22. out.println("</HTML>");
23. }
24. }
web.xml
1. <web-app>
2. <listener>
3. <listener-class>com.matrix.SessionLifeCycleEventDemo</listener-class>
4. </listener>
5. <servlet>
RIX
AT
M
6. <servlet-name>UserCounter</servlet-name>
7. <servlet-class>com.matrix.UserCounterServlet</servlet-class>
8. </servlet>
9. <servlet-mapping>
10. <servlet-name>UserCounter</servlet-name>
11. <url-pattern>/usercounter</url-pattern>
12. </servlet-mapping>
13. </web-app>
Example 20:-
index.html
1. <html><body>
2. <a href=servlet1>Click here for Session Listener</a>
3. </body></html>
Servlet1.java
1. package com.matrix;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. import javax.servlet.http.HttpSession;
9. public class Servlet1 extends HttpServlet
10. {
11. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
12. {
13. PrintWriter out=response.getWriter();
14. HttpSession session=request.getSession();
15. session.setAttribute("name", "Matrix Research");
16. session.setAttribute("name", "Matrix Research and Computers");
17. String name=(String)session.getAttribute("name");
18. out.print("The Attribute is: "+name);
19. out.print("<br>");
20. session.removeAttribute("name");
RIX
AT
M
21. session.invalidate();
22. out.print("Check logs for session events");
23. }
24. }
Session11.java
1. package com.matrix;
2. import javax.servlet.http.HttpSessionEvent;
3. import javax.servlet.http.HttpSessionListener;
4. public class Session11 implements HttpSessionListener
5. {
6. public void sessionCreated(HttpSessionEvent arg)
7. {
8. System.out.println("Session Created");
9. }
10. public void sessionDestroyed(HttpSessionEvent arg)
11. {
12. System.out.println("Session Destroyed");
13. }
14. }
SessionAttrib11.java
1. package com.matrix;
2. import javax.servlet.http.HttpSessionAttributeListener;
3. import javax.servlet.http.HttpSessionBindingEvent;
Matrix Computers (Page 87 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
12. <servlet-mapping>
13. <servlet-name>servlet1</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. </web-app>
3. import java.io.PrintWriter;
4. import javax.servlet.ServletException;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class Servlet1 extends HttpServlet
9. {
10. protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
11. {
12. String firstname=request.getParameter("firstname");
13. String lastname=request.getParameter("lastname");
14. PrintWriter out=response.getWriter();
15. out.print(firstname);
16. out.print("<br>");
17. out.print(lastname);
18. out.print("<br>");
19. request.setAttribute("user", "Matrix Computers");
20. request.setAttribute("user", "Matrix Computers and Research");//Replacing the attribute
21. String user=(String)request.getAttribute("user");
22. out.print(user);
23. request.removeAttribute("user");
24. }
25. }
ListeningRequest.java
1. package com.matrix;
2. import javax.servlet.ServletRequestEvent;
3. import javax.servlet.ServletRequestListener;
4. public class ListeningRequest implements ServletRequestListener
5. {
6. public void requestInitialized(ServletRequestEvent arg0)
7. {
RIX
AT
M
8. System.out.println("Request Initialized");
9. }
10. public void requestDestroyed(ServletRequestEvent arg0)
11. {
12. System.out.println("Request Destroyed");
13. }
14. }
ListeningAttribute.java
1. package com.matrix;
2. import javax.servlet.ServletRequestAttributeEvent;
3. import javax.servlet.ServletRequestAttributeListener;
4. public class ListeningAttributes implements ServletRequestAttributeListener
5. {
6. public void attributeAdded(ServletRequestAttributeEvent arg0)
7. {
8. String name=arg0.getName();
9. String value=(String)arg0.getValue();
10. System.out.println("Attribute : "+name +" Added and The Value is : "+value);
11. }
12. public void attributeRemoved(ServletRequestAttributeEvent arg0)
13. {
14. String name=arg0.getName();
15. System.out.println("Attribute "+name+" Removed");
16. }
Matrix Computers (Page 89 of 90)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
RequestListener:-
For listening request related events, there are two interfaces in javax.servlet package.
1. javax.servlet.ServletRequestListener
2. javax.servlet.ServletRequestAttributeListener
To see the changes while we are sending request to a servlet or any static/web resource, there is an interface in
javax.servlet package.
RIX
AT
M
Methods:-
• void requestInitialized(ServletRequestEvent sre):-Notification that the servlet request is about to go into scope.
• void requestDestroyed(ServletRequestEvent sre):-Notification that the servlet request is about to go out of
scope.
These two methods have an Event class as a parameter. The event class object initialized when an event happens.
public class ServletRequestEvent extends EventObject:-This is the event class for notifications
about changes to the servlet request of a web application.
Methods:-
• ServletContext getServletContext():-Return the ServletContext that changed.
• ServletRequest getServletRequest():-Return the ServletRequest that changed.
To listens about attributes added or removed in request object. The following interface in javax.servlet package for
listening attributes of request object:
Methods:-
• void attributeAdded(ServletRequestAttributeEvent srae) :-Notification that a new attribute was added to the
servlet request.
• void attributeRemoved(ServletRequestAttributeEvent srae):-Notification that an existing attribute has been
removed from the servlet request.
• void attributeReplaced(ServletRequestAttributeEvent srae):-Notification that an attribute on the servlet request
has been replaced.
Methods:-
• String getName():-Return the name of the attribute that changed on the ServletRequest.
• Object getValue():-Returns the value of the attribute that has been added removed or replaced.
RIX
AT
M