Servlet Interview Questions
Servlet Interview Questions
==================================================================
A web server responsibility is to handler HTTP requests from client browsers and respond with
HTML response. A web server understands HTTP language and runs on HTTP protocol.
Apache Web Server is kind of a web server and then we have specific containers that can
execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS
Messaging support, Transaction Management etc. So we can say that Application server is a web
server with additional functionalities to help developers with enterprise applications.
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods
GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement
our application to make sure these methods always return same result. HTTP method POST is
non-idempotent method and we should use post method when implementing something that
changes with every request.
For example, to access an HTML page or image, we should use GET because it will always
return the same object but if we have to save customer information to database, we should use
POST method. Idempotent methods are also known as safe methods and we don’t care about the
repetitive request from the client for safe methods.
The “Content-Type” response header is known as MIME Type. Server sends MIME type to
client to let them know the kind of data it’s sending. It helps client in rendering the data for user.
Some of the mostly used mime types are text/html, text/xml, application/xml etc.
We can use ServletContext getMimeType() method to get the correct MIME type of the file and
use it to set the response content type. It’s very useful in downloading file through servlet from
server.
Web Applications are modules that run on server to provide both static and dynamic content to
the client browser. Apache web server supports PHP and we can create web application using
PHP. Java provides web application support through Servlets and JSPs that can run in a servlet
container and provide dynamic content to client browser.
Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like
below image.
6).What is a servlet?
Java Servlet is server side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods. When implementing a generic service, we can extend the GenericServlet class provided
with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and
doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly
extend HttpServlet class. Servlet API hierarchy is shown in below image.
Servlets provide better performance that CGI in terms of processing time, memory
utilization because servlets uses benefits of multithreading and for each request a new
thread is created, that is faster than loading creating new Object for each request with CGI.
Servlets and platform and system independent, the web application developed with Servlet
can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on
operating systems such as Windows, Linux, Unix, Solaris, Mac etc.
Servlets are robust because container takes care of life cycle of servlet and we don’t need
to worry about memory leaks, security, garbage collection etc.
Servlets are maintainable and learning curve is small because all we need to take care is
business logic for our application.
Servlet containers are also known as web container, for example Tomcat. Some of the
important tasks of servlet container are:
RequestDispatcher interface is used to forward the request to another resource that can be
HTML, JSP or another servlet in same application. We can also use this to include the
content of another resource to the response. This interface is used for inter-servlet
communication in the same context.
We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can
use ServletResponse getOutputStream() method to get the ServletOutputStream object
reference.
We can’t get instances of both PrintWriter and ServletOutputStream in a single servlet method, if
we invoke both the methods; getWriter() and getOutputStream() on response; we will
get java.lang.IllegalStateException at runtime with message as other method has already been
called for this response.
We can create deadlock in servlet by making a loop of method invocation, just call doPost()
method from doGet() method and doGet() method to doPost() method to create deadlock
situation in servlet.
SingleThreadModel interface was provided for thread safety and it guarantees that no two
threads will execute concurrently in the servlet’s service method. However SingleThreadModel
does not solve all thread safety issues. For example, session attributes and static variables can
still be accessed by multiple requests on multiple threads at the same time, even when
SingleThreadModel servlets are used. Also it takes out all the benefits of multithreading support
of servlets, thats why this interface is Deprecated in Servlet 2.4.
When servlet container receives client request, it invokes the service() method which in
turn invokes the doGet(), doPost() methods based on the HTTP method of request. I don’t
see any use case where we would like to override service() method. The whole purpose of
service() method is to forward to request to corresponding HTTP method implementations.
If we have to do some pre-processing of request, we can always use servlet filters and
listeners.
We can define a constructor for servlet but I don’t think its of any use because we won’t be
having access to the ServletConfig object until unless servlet is initialized by container.
Ideally if we have to initialize any resource for servlet, we should override init() method
where we can access servlet init parameters using ServletConfig object.
When we want to invoke another servlet from a servlet service methods, we use inter-
servlet communication mechanisms. We can invoke another servlet using
RequestDispatcher forward() and include() methods and provide additional attributes in
request for other servlet use.
21) Are Servlets Thread Safe? How to achieve thread safety in servlets?
HttpServlet init() method and destroy() method are called only once in servlet life cycle, so we
don’t need to worry about their synchronization. But service methods such as doGet() or
doPost() are getting called in every client request and since servlet uses multithreading, we
should provide thread safety in these methods.
If there are any local variables in service methods, we don’t need to worry about their thread
safety because they are specific to each thread but if we have a shared resource then we can use
synchronization to achieve thread safety in servlets when working with shared resources.
Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes
in web application. There are three scopes for servlet attributes – request scope, session scope
and application scope.
Servlet attributes are different from init parameters defined in web.xml for ServletConfig or
ServletContext.
We can’t use RequestDispatcher to invoke servlet from another application because it’s specific
for the application. If we have to forward the request to a resource in another application, we can
use ServletResponse sendRedirect() method and provide complete URL of another servlet. This
sends the response to client with response code as 302 to forward the request to another URL. If
we have to send some data also, we can use cookies that will be part of the servlet response and
sent in the request to another servlet.
HttpServlet class provide HTTP protocol implementation of servlet but it’s left abstract because
there is no implementation logic in service methods such as doGet() and doPost() and we should
override at least one of the service methods. That’s why there is no point in having an instance of
HttpServlet and is declared abstract class.
We know that Servlet Container manages the life cycle of Servlet, there are four phases of
servlet life cycle.
1. Servlet Class Loading – When container receives request for a servlet, it first loads the
class into memory and calls it’s default no-args constructor.
2. Servlet Class Initialization – Once the servlet class is loaded, container initializes the
ServletContext object for the servlet and then invoke it’s init method by passing servlet
config object. This is the place where a servlet class transforms from normal class to
servlet.
3. Request Handling – Once servlet is initialized, its ready to handle the client requests. For
every client request, servlet container spawns a new thread and invokes the service()
method by passing the request and response object reference.
4. Removal from Service – When container stops or we stop the application, servlet container
destroys the servlet class by invoking it’s destroy() method.
1. public void init(ServletConfig config) – This method is used by container to initialize the
servlet, this method is invoked only once in the lifecycle of servlet.
2. public void service(ServletRequest request, ServletResponse response) – This method is
called once for every request, container can’t invoke service() method until unless init()
method is executed.
3. public void destroy() – This method is invoked once when servlet is unloaded from
memory.
29)What are life cycle methods of a servlet?
If we have to initialize some resource before we want our servlet to process client requests,
we should override init() method. If we override init(ServletConfig config) method, then
the first statement should be super(config) to make sure superclass init(ServletConfig
config) method is invoked first. That’s why GenericServlet provides another helper init()
method without argument that get’s called at the end of init(ServletConfig config) method.
We should always utilize this method for overriding init() method to avoid any issues as
we may forget to add super() call in overriding init method with ServletConfig argument.
Session is a conversional state between client and server and it can consists of multiple request
and response between client and server. Since HTTP and Web Server both are stateless, the only
way to maintain a session is when some unique information about the session (session id) is
passed between server and client in every request and response.
We can use HttpSession for session management in servlets but it works with Cookies and we
can disable the cookie in client browser. Servlet API provides support for URL rewriting that we
can use to manage session in this case.
The best part is that from coding point of view, it’s very easy to use and involves one step –
encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback
approach and it kicks in only if browser cookies are disabled.
We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect
the request to another resource and we want to provide session information, we can use
encodeRedirectURL() method.
Index.html
<form action="servlet1">
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
Web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
33) How does Cookies work in Servlets?
Cookies are used a lot in web client-server communication, it’s not something specific to java.
Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.http.Cookie class that implements
Serializable and Cloneable interfaces.
HttpServletRequest getCookies() method is provided to get the array of Cookies from request,
since there is no point of adding Cookie to request, there are no methods to set or add cookie to
request.
Index.html
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
Web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
34) Hidden Form Filed in servlets?
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of
an user.
n such case, we store the information in the hidden field and get it from another servlet. This
approach is better if we have to submit form in all the pages and we don't want to depend on the
browser.
Let's see the code to store value in hidden field
<input type="hidden" name="uname" value="rajkumar">
It is widely used in comment form of a website. In such case, we store page id or page name in
the hidden field so that each page can be uniquely identified.
Advantage:
It will always work whether cookie is disabled or not.
Disadvantage:
It is maintained at server side.Extra form submission is required on each pages.Only textual
information can be used.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Session tracking is used to maintain a state on the series of requests from the same user for a
given period of time.
38) Why session tracking is needed?
Every HTTP request needs to be captured by HTTP protocol and for that, state is captured.
Tracking of state is called session tracking.
URL rewriting
Hidden Form Fields
Cookies
Secure Socket Layer (SSL)
Cookies are used to store long term information that can be maintained without server
interaction. Small and Medium size data are kept in a queue.
URL rewriting is one of the methods of session tracking in which additional data is appended at
the end of each URL. This additional data identifies the session.
A servlet container which does not initialize at the start up, this is known as servlet lazy loading.
Chaining is one of the methods where out of one servlet is given to the second servlet. This
chaining can happen for any number of servlets.
Security check
Modifying the request or response
Data compression
Logging and auditing
Response compression
Lifecycle management
Communication support
Multithreading support
Declarative security
JSP support
JSP supports HTTP protocol which mainly used for presentation. But a servlet can support any
protocol like HTTP, FTP, SMTP etc.
A server can provide service to the client and it contains one or more containers such as EJBs,
Servlet, JSP containers. Containers hold set of objects.
On the client side, Meta http is used for refresh and server push is used for server side refresh.
ServletConfig provides information about configuration of a servlet which is defined inside the
web.xml file and it is a specific object for each servlet.
ServletContext is an application specific object and it is shared by all servlet. It belongs to one
application in one JVM
1) forward() sends the same request to 1) sendRedirect() method sends new request always bec
another resource. bar of the browser.
2) forward() method works at server side. 2) sendRedirect() method works at client side.
3) forward() method works within the server 3) sendRedirect() method works within and outside the s
only.
51) What are the annotations used in Servlet 3?
52). What is the difference between Servlet Request and Servlet Context when calling a
Request Dispatcher?
Relative URL can be called when Servlet Request is used and Relative URL is not used when
using Servlet Context.
53). What are the features added in Servlet 2.5?
Security check
Modifying the request or response
Data compression
Logging and auditing
Response compression
Lifecycle management
Communication support
Multithreading support
Declarative security
JSP support
ServletConfig provides information about configuration of a servlet which is defined inside the
web.xml file and it is a specific object for each servlet.
ServletContext is an application specific object and it is shared by all servlet. It belongs to one
application in one JVM
60). What are the different mode that servlets can be used?
61) Why super.init (config) is the first statement inside init(config) method.
This will be the first statement if we are overriding the init(config) method by this way
we will store the config object for future reference and we can use by getServletConfig()
to get information about config object if will not do this config object will be lost and we
have only one way to get config object because servlet pass config object only in init
method . Without doing this if we call the ServletConfig method will
get NullPointerException.
62) Can we call destroy() method inside the init() method is yes what will happen?
Yes we can call like this but if we have not overridden this method container
will call the default method and nothing will happen.after calling this if any we
have overridden the method then the code written inside is executed.
63) How can you get the information about one servlet context in another servlet?
In context object we can set the attribute which we want on another servlet and
64) Why we need to implement Single Thread model in the case of Servlet
Ans: In J2EE we can implement our servlet in two different ways either by using:
1. Single Thread Model
2. Multithread Model
Depending upon our scenario, if we have implemented single thread means only one
instance is going handle one request at a time no two thread will concurrently execute
service method of the servlet.
The example in banking accounts where sensitive data is handled mostly this scenario
was used this interface is deprecated in Servlet API version 2.4.
ServletContext is an application specific object which is shared by all the servlet belongs
to one application in one JVM .this is a single object which represents our application and
all the servlet access application specific data using this object.servlet also use their
method to communicate with the container.
1. What is Filter ?
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption
and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the
entry of filter from the web.xml file, filter will be removed automatically and we don't need to
change the servlet.
Servlet Filters are Java classes that can be used in Servlet Programming for the following
purposes −
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
2. Types Of Filter.
Authentication Filters.
Data compression Filters.
Encryption Filters.
Filters that trigger resource access events.
Image Conversion Filters.
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
3. Usage of Filter
4. Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance.
5. Filter API
Like Servlet filter have its own API. The javax.servlet package contains the three interfaces of
Filter API.
1. Filter
2. FilterChain
3. FilterConfig
1) Filter Interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life
cycle methods for a filter.
Method Description
(i) public void init(FilterConfig config) init() This method is invoked only once. It is used
to initialize the filter. Or This method is called by
the web container to indicate to a filter that it is
being placed into service.
(ii) public void doFilter(HttpServletRequest doFilter() method is invoked every time when
request,HttpServletResponse response, user request to any resource, to which the filter is
FilterChain chain) mapped. It is used to perform filtering tasks.
2) FilterChain Interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This
object is passed in the doFilter method of Filter interface.The FilterChain interface contains only
one method:
3) FilterConfig Interface
An object of FilterConfig is created by the web container. This object can be used to get the
configuration information from the web.xml file.
1. public void init(FilterConfig config): init() method is invoked only once it is used to
initialize the filter.
2. public String getInitParameter(String parameterName): Returns the parameter value
for the specified parameter name.
3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration
containing all the parameter names.
4. public ServletContext getServletContext(): Returns the ServletContext object.
Example of FilterConfig
In this example, if you change the param-value to no, request will be forwarded to the servlet
otherwise filter will create the response with the message: this page is underprocessing. Let's see
the simple example of FilterConfig. Here, we have created 4 files:
index.html
MyFilter.java
HelloServlet.java
web.xml
index.html
MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7. FilterConfig config;
8.
9. public void init(FilterConfig config) throws ServletException {
10. this.config=config;
11. }
12.
13. public void doFilter(ServletRequest req, ServletResponse resp,
14. FilterChain chain) throws IOException, ServletException {
15.
16. PrintWriter out=resp.getWriter();
17.
18. String s=config.getInitParameter("construction");
19.
20. if(s.equals("yes")){
21. out.print("This page is under construction");
22. }
23. else{
24. chain.doFilter(req, resp);//sends request to next resource
25. }
26.
27. }
28. public void destroy() {}
29. }
HelloServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
5. public class HelloServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. out.print("<br>welcome to servlet<br>");
11.
12. }
13.
14. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>HelloServlet</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>HelloServlet</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. <init-param>
17. <param-name>construction</param-name>
18. <param-value>no</param-value>
19. </init-param>
20. </filter>
21. <filter-mapping>
22. <filter-name>f1</filter-name>
23. <url-pattern>/servlet1</url-pattern>
24. </filter-mapping>
25.
26.
27. </web-app>
Following is the Servlet Filter Example that would print the clients IP address and current
date time.
Application 4 :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
Compile LogFilter.java in usual way and put your class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is
defined and then mapped to a URL pattern. Create the following entry for filter tag in the
deployment descriptor file web.xml
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above filter would apply to all the servlets because we specified /* in our configuration. You
can specicy a particular servlet path if you want to apply filter on few servlets only.
Your web application may define several different filters with a specific purpose. Consider, you
define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained
above except you need to create a different mapping as mentioned below −
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The order of filter-mapping elements in web.xml determines the order in which the web
container applies the filter to the servlet. To reverse the order of the filter, you just need to
reverse the filter-mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to
any servlet but the following example would reverse the order −
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
We can define filter same as Servlet. Let's see the elements of filter and filter-mapping.
1. <web-app>
2. <filter>
3. <filter-name>...</filter-name>
4. <filter-class>...</filter-class>
5. </filter>
6. <filter-mapping>
7. <filter-name>...</filter-name>
8. <url-pattern>...</url-pattern>
9. </filter-mapping>
10. </web-app>
For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an
advantage over servlet-name element i.e. it can be applied on servlet, JSP or HTML.
Application 1:
Step1# index.html
Step2# MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6. public void doFilter(ServletRequest req, ServletResponse resp,
7. FilterChain chain) throws IOException, ServletException {
8. PrintWriter out=resp.getWriter();
9. out.print("filter is invoked before");
10. chain.doFilter(req, resp);//sends request to next resource
11. out.print("filter is invoked after");
12. }
13. public void destroy() {}
14. }
Step3# HelloServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
5. public class HelloServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. out.print("<br>welcome to servlet<br>");
11. }
12. }
Step4# web.xml
For defining the filter, filter element of web-app must be defined just like servlet.
1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>HelloServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <filter>
11. <filter-name>f1</filter-name>
12. <filter-class>MyFilter</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/servlet1</url-pattern>
17. </filter-mapping>
18. </web-app>
Authentication Filter
We can perform authentication in filter. Here, we are going to check to password given by the
user in filter class, if given password is admin, it will forward the request to the WelcomeAdmin
servlet otherwise it will display error message.
Application 2 :
index.html
MyFilter.java
AdminServlet.java
web.xml
Step1# index.html
1. <form action="servlet1">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="password"/><br/>
4. <input type="submit" value="login">
5. </form>
Step2# MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6. public void doFilter(ServletRequest req, ServletResponse resp,
7. FilterChain chain) throws IOException, ServletException {
8. PrintWriter out=resp.getWriter();
9. String password=req.getParameter("password");
10. if(password.equals("admin")){
11. chain.doFilter(req, resp);//sends request to next resource
12. }
13. else{
14. out.print("username or password error!");
15. RequestDispatcher rd=req.getRequestDispatcher("index.html");
16. rd.include(req, resp);
17. }
18. }
19. public void destroy() {}
20. }
Step3# : AdminServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
5. public class AdminServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. out.print("welcome ADMIN");
11. out.close();
12. }
13. }
Step4# : web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>AdminServlet</servlet-name>
4. <servlet-class>AdminServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>AdminServlet</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <filter>
11. <filter-name>f1</filter-name>
12. <filter-class>MyFilter</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/servlet1</url-pattern>
17. </filter-mapping>
18. </web-app>
Application 3:
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6.
7. public void doFilter(ServletRequest req, ServletResponse res,
8. FilterChain chain) throws IOException, ServletException {
9.
10. PrintWriter out=res.getWriter();
11.
12. out.print("<br/>this site is underconstruction..");
13. out.close();
14.
15. }
16. public void destroy() {}
17. }
Application 4:
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
6. public void init(FilterConfig arg0) throws ServletException {}
7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=res.getWriter();
12. chain.doFilter(request,response);
13.
14. out.print("<br/>Total visitors "+(++count));
15. out.close();
16.
17. }
18. public void destroy() {}
19. }
Application 5:
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3. public class MyFilter implements Filter{
4. static int count=0;
5. public void init(FilterConfig arg0) throws ServletException {}
6. public void doFilter(ServletRequest req, ServletResponse res,
7. FilterChain chain) throws IOException, ServletException {
8. PrintWriter out=res.getWriter();
9. long before=System.currentTimeMillis();
10. chain.doFilter(request,response);
11. long after=System.currentTimeMillis();
12. out.print("<br/>Total response time "+(after-before)+" miliseconds");
13. out.close();
14. }
15. public void destroy() {}
16. }
17.
Events are basically occurrence of something. Changing the state of an object is known as an
event.
We can perform some important tasks at the occurrence of these exceptions, such as counting
total and current logged-in users, creating tables of the database at time of deploying the project,
creating database connection object etc.
There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http
packages.
Event classes
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
Event Interfaces
1. ServletRequestListener.
2. ServletRequestAttributeListener.
3. ServletContextListener.
4. ServletContextAttributeListener.
5. HttpSessionListener.
6. HttpSessionAttributeListener.
7. HttpSessionBindingListener.
8. HttpSessionActivationListener.
If you want to perform some action at the time of deploying the web application such as creating
database connection, creating all the tables of the project etc, you need to implement
ServletContextListener interface and provide the implementation of its methods.
There is only one constructor defined in the ServletContextEvent class. The web container
creates the instance of ServletContextEvent after the ServletContext instance.
1. ServletContextEvent(ServletContext e)
There are two methods declared in the ServletContextListener interface which must be
implemented by the servlet programmer to perform some action such as creating database
connection etc.
In this example, we are retrieving the data from the emp32 table. To serve this, we have created
the connection object in the listener class and used the connection object in the servlet.
index.html
MyListener.java
1. import javax.servlet.*;
2. import java.sql.*;
3.
4. public class MyListener implements ServletContextListener{
5. public void contextInitialized(ServletContextEvent event) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. //storing connection object as an attribute in ServletContext
12. ServletContext ctx=event.getServletContext();
13. ctx.setAttribute("mycon", con);
14.
15. }catch(Exception e){e.printStackTrace();}
16. }
17.
18. public void contextDestroyed(ServletContextEvent arg0) {}
19. }
MyListener.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. import java.sql.*;
5.
6. public class FetchData extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. try{
15. //Retrieving connection object from ServletContext object
16. ServletContext ctx=getServletContext();
17. Connection con=(Connection)ctx.getAttribute("mycon");
In this example, we are creating table of the project. So we don't need to create all the tables
manually in the database.
MyListener.java
1. import javax.servlet.*;
2. import java.sql.*;
3. public class MyListener implements ServletContextListener{
4. public void contextInitialized(ServletContextEvent arg0) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection("
8. jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. String query="create table emp32(id number(10),name varchar2(40))";
10. PreparedStatement ps=con.prepareStatement(query);
11. ps.executeUpdate();
12. System.out.println(query);
13. }catch(Exception e){e.printStackTrace();}
14. }
15. public void contextDestroyed(ServletContextEvent arg0) {
16. System.out.println("project undeployed");
17. }
18. }
Servlet Filters are Java classes that can be used in Servlet Programming for the following
purposes −
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet
names or URL patterns in your application's deployment descriptor.
When the web container starts up your web application, it creates an instance of each filter that
you have declared in the deployment descriptor. The filters execute in the order that they are
declared in the deployment descriptor.
A filter is simply a Java class that implements the javax.servlet.Filter interface. The
javax.servlet.Filter interface defines three methods −
This method is called by the web container to indicate to a filter that it is being taken out
3 of service.
Following is the Servlet Filter Example that would print the clients IP address and current date
time. This example would give you basic understanding of Servlet Filter, but you can write more
sophisticated filter applications using the same concept −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
Compile LogFilter.java in usual way and put your class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is
defined and then mapped to a URL pattern. Create the following entry for filter tag in the
deployment descriptor file web.xml
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above filter would apply to all the servlets because we specified /* in our configuration. You
can specicy a particular servlet path if you want to apply filter on few servlets only.
Now try to call any servlet in usual way and you would see generated log in your web server log.
You can use Log4J logger to log above log in a separate file.
Your web application may define several different filters with a specific purpose. Consider, you
define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained
above except you need to create a different mapping as mentioned below −
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The order of filter-mapping elements in web.xml determines the order in which the web
container applies the filter to the servlet. To reverse the order of the filter, you just need to
reverse the filter-mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to
any servlet but the following example would reverse the order −
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Listener:
1. What is the use of listener in Java?
Listeners do some work when an event occurs. They are called as "Event Listeners". Events
like click, hover etc. For Example, we have ActionListener interface in Java. It calls
actionPerformed() method when an event occurs.
Servlet Listener is used for listening to events in a web containers, such as when you create a
session, or place an attribute in an session or if you passivate and activate in another container, to
subscribe to these events you can configure listener in web.xml , for example
HttpSessionListener .
Listener Classes get notified on selected events, such as starting up the application or creating a
new Session. Listener Classes : These are simple Java classes which implement one of the two
following interfaces : javax.servlet.ServletContextListener.
javax.servlet.http.HttpSessionListener.Se
2. What is the event listener?
An event listener is a procedure or function in a computer program that waits for an event to
occur; that event may be a user clicking or moving the mouse, pressing a key on the keyboard, or
an internal timer or interrupt. The listener is in effect a loop that is programmed to react to an
input or signal
Listener Classes get notified on selected events, such as starting up the application or creating a
new Session.
Listener Classes :
These are simple Java classes which implement one of the two following interfaces :
javax.servlet.ServletContextListener
javax.servlet.http.HttpSessionListener
If you want your class to listen for application startup and shutdown events then implement
ServletContextListener interface. If you want your class to listen for session creation and
invalidation events then implement HttpSessionListener interface.
Servlet Filter is used for monitoring request and response from client to the servlet, or to modify
the request and response, or to audit and log.
Servlet Listener is used for listening to events in a web containers, such as when you create a
session, or place an attribute in an session or if you passivate and activate in another container, to
subscribe to these events you can configure listener in web.xml, for example HttpSessionListener
Servlet Filters are pluggable java components that we can use to intercept and process requests
before they are sent to servlets and response after servlet code is finished and before container
sends the response back to the client.
Some common tasks that we can do with filters are:
We know that using ServletContext, we can create an attribute with application scope that all
other servlets can access but we can initialize ServletContext init parameters as String only in
deployment descriptor (web.xml). What if our application is database oriented and we want to set
an attribute in ServletContext for Database Connection.
If you application has a single entry point (user login), then you can do it in the first servlet
request but if we have multiple entry points then doing it everywhere will result in a lot of code
redundancy. Also if database is down or not configured properly, we won’t know until first client
request comes to server. To handle these scenario, servlet API provides Listener interfaces that
we can implement and configure to listen to an event and do certain operations.
1. Filter
Filter Servlet is the server javax.servlet.Filter interface, is the main purpose of the filtration
character encoding, do some business logic judgment. Its working principle is, as long as you
request
in the web.xml configuration files to intercept the client, it will help you to intercept the request,
you can request or response (Request, Response) unified set of code, simplify operation; also can
be logical judgment, as the user is logged in or not, there is no authority access the page etc. It is
start with the web start the application you, initialized only once, can intercept related request,
only is destroyed when the web application you stop or redeployment, following by filtering the
code example to understand its use:
MyCharsetFilter.java
package ...;
import ...;
//Main purpose: filtration character encoding; secondly, to do some application logic. making
// Filter with web application together to start making
// when web application restart or destroyed, Filter also destroyed making
public class MyCharsetFilter implements Filter {
private FilterConfig config = null;
public void destroy() {
System.out.println("MyCharsetFilter is ready to destroy...");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOEx
ception, ServletException {
// casts making
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
// gets web.xm setup code set, set to Request, Response making
request.setCharacterEncoding(config.getInitParameter("charset"));
response.setContentType(config.getInitParameter("contentType"));
response.setCharacterEncoding(config.getInitParameter("charset"));
// forwards the request to the destination making
chain.doFilter(request, response);
}
1. <filter>
2. <filter-name>filter</filter-name>
3. <filter-class>dc.gz.filters.MyCharsetFilter</filter-class>
4. <init-param>
5. <param-name>charset</param-name>
6. <param-value>UTF-8</param-value>
7. </init-param>
8. <init-param>
9. <param-name>contentType</param-name>
10. <param-value>text/html;charset=UTF-8</param-value>
11. </init-param>
12. </filter>
13. <filter-mapping>
14. <filter-name>filter</filter-name>
15. <!-- * request all representative intercepted or specify request/test.do /xxx.do --
>
16. <url-pattern>/*</url-pattern>
17. </filter-mapping>
2. listeners
Now about the Servlet listener Listener, it is the realization of the server
javax.servlet.ServletContextListener interface, it is also with the web application startup
and restart, initialized only once, and the destruction of web application with the stop.
Main function is: do some initialization work content, set some of its basic contents, such
as the number of parameters or some fixed object etc. The use of database connection
pool using the listener DataSource initialization demo of it:
MyServletContextListener.java
package dc.gz.listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.dbcp.BasicDataSource;
/**
Making * listener making Web application
*/
public class MyServletContextListener implements ServletContextListener {
//Method of destruction application listener making
public void contextDestroyed(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
// call before the destruction of the entire web, all applications will be space setting
emptied of its contents making
sc.removeAttribute("dataSource");
System.out.println("The destruction of the work completed...");
}
bds.setDriverClassName("com.mysql.jdbc.Driver"); bds.setUrl("jdbc:mysql
://localhost:3306/hibernate");
bds.setUsername("root");
bds.setPassword("root");
bds.setMaxActive(10);//The maximum number of connections making
bds.setMaxIdle(5);//The maximum number of making management
//bds.setMaxWait(maxWait); maximum waiting time making
//The DataSource in ServletContext space,
//The use of for the entire web application (for the database connection) aking
sc.setAttribute("dataSource", bds);
System.out.println("Application Monitor initialization completed...");
System.out.println("DataSource has already been created...");
}
The web.xml configuration is as follows, very simple:
Thus configured, then can be used in Web BasicDataSource object through the
ServletContext, so as to get connected, and improve database performance, ease of use.
3 . interceptor
22. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
23. {
24. Object result = null;
25. System.out.println("before invoke method :" + method.getName());
26. result = method.invoke(this.targetObj, args);
27. System.out.println("after invoke method : " + method.getName());
28. return result;
29. }
1: the so-called filter is used to filter filter name, In the Java Web, You pass the request,
response to filter out some information, Or to set some parameters, And then passed to
the servlet or struts action for business logic, For example, filter out illegal URL (not the
login.do address request, If the user does not have the landing are filtered out), or in the
incoming servlet or struts before the action set character set, Or remove some illegal
characters (chat rooms are often used, Some curse words). The filter process is linear,
then, URL came to check, maintain the original process continue execution, is the next
filter, servlet reception.
2. listeners: this thing is often used in c/s mode, he will produce a treatment for specific
events. Monitoring used in many mode. For example, the observer pattern, is a listening
to. For instance struts can be used to monitor to start. The Servlet listener listens for some
important events, the listener object can do some processing can occur before it
happened, after.
3.java interceptor is mainly used in plug-ins, extensions such as hivernate spring Struts2
are similar for slicing technique, to something in the configuration file or XML file
statement section before using.