Servlets Interview Questions with Answers


Q) Servlet
            Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Servlets will be loaded in the Address space of web server.
à Servlet are loaded 3 ways 1) When the web sever starts 2) You can set this in the configuration file 3) Through an administration interface.

Q) What is Temporary Servlet?
A) When we sent a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use following command.
Java weblogic.jspc—keepgenerated *.jsp

Q) What is the difference between Server and Container?
A) A server provides many services to the clients, A server may contain one or more containers such as ejb containers, servlet/jsp container. Here a container holds a set of objects.

Q) Servlet Container
            The servlet container is a part of a Web server (or) Application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
A servlet container can be built into a host Web server, or installed as an add-on component to a Web Server via that server’s native extension API. All servlet containers must support HTTP as a protocol for requests and
responses, but additional request/response-based protocols such as HTTPS (HTTP over SSL) may be supported.

Q) Generally Servlets are used for complete HTML generation. If you want to generate partial HTML's that include some static text as well as some dynamic text, what method do you use?
A) Using 'RequestDispather.include(“xx.html”) in the servlet code we can mix the partial static HTML Directory page.
Ex: - RequestDispatcher rd=ServletContext.getRequestDispatcher(“xx.html”);
 rd.include(request,response);

Q) Servlet Life cycle

Public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()

à The Web server when loading the servlet calls the init method once. (The init method typically establishes database connections.)

àAny request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet. If u put “Private” modifier for the service() it will give compile time error.

à When your application is stopped (or) Servlet Container shuts down, your Servlet's destroy () method will be called. This allows you to free any resources you may have got hold of in your Servlet's init () method, this will call only once.

ServletException à Signals that some error occurred during the processing of the request and the container should take appropriate measures to clean up the request.

 IOException à Signals that Servlet is unable to handle requests either temporarily or permanently.

Q) Why there is no constructor in servlet?
A) A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.

Q) Can we use the constructor, instead of init(), to initialize servlet?
A) Yes, of course you can use. There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor?
A) No, because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.

Q) Directory Structure of Web Applications?
A)         WebApp/(Publicly available files, such as
                    |  .jsp, .html, .jpg, .gif)
                    |
                    +WEB-INF/-+
                              |
                              + classes/(Java classes, Servlets)
                              |
                              + lib/(jar files)
                              |
                              + web.xml / (taglib.tld)
                              |
                              + weblogic.xml
   
     WAR-> WARfile can be placed in a server’s webapps directory

Q) Web.xml: -
<web-app>
<!-- Defines WebApp initialization parameters.-->
<context-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</context-param>

<!-- Defines filters and specifies filter mapping -->
<filter>
<filter-name>Test Filter</filter-name>
<filter-class>filters.TestFilter</filter-class>

<init-param>
      <param-name>locale</param-name>
                   <param-value>US</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Test Filter</filter-name>
<servlet-name>TestServlet</servlet-name>
</filter-mapping>

<!-- Defines application events listeners -->
<listener>
    <listener-class>
listeners.MyServletContextListener</listener-class>
    </listener>
<listener>
    <listener-class>
listeners.MySessionCumContextListener
    </listener-class>
</listener>

<!-- Defines servlets -->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlets.HelloServlet</servlet-class>

<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
    <security-role-ref>
<!-- role-name is used in HttpServletRequest.isUserInRole(String role) method. -->
<role-name>manager</role-name>
<!-- role-link is one of the role-names specified in security-role elements. -->
<role-link>supervisor</role-link>
   </security-role-ref>
</servlet>

<!-- Defines servlet mappings -->
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>*.hello</url-pattern>
</servlet-mapping>

<!--specifies session timeout as 30 minutes. -->
<session-config>
<session-timeout>30</session-timeout>
<session-config>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<! -- Error page -- >
<error-page>
<error-code>404</error-code>
<location>notfoundpage.jsp</location>
</error-page>

<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>sqlexception.jsp</location>
</error-page>

<taglib>
<taglib-uri>http://abc.com/testlib</taglib-uri>
<taglib-location>/WEB-INF/tlds/testlib.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/examplelib</taglib-uri>
<taglib-location>/WEB-INF/tlds/examplelib.tld</taglib-location>
</taglib>

<!-- only POST method is protected -->
<http-method>POST</http-method>

<web-resource-collection>
<web-resource-name>Another Protected Area</web-resource-name>
<url-pattern>*.hello</url-pattern>
</web-resource-collection>

<!-- auth-method can be: BASIC, FORM, DIGEST, or CLIENT-CERT -->
<auth-method>FORM</auth-method>
<realm-name>sales</realm-name>
     <form-login-config>
<form-login-page>/formlogin.html</form-login-page>
<form-error-page>/formerror.jsp</form-error-page>
     </form-login-config>
</login-config>

</web-app>

Q) Automatically start Servlet?
A) If present, calls the servlet's service() method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.
The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use:
 
<servlet servlet-name='test.HelloWorld'>
  <run-at>0:00, 6:00, 12:00, 18:00</run-at>
</servlet>

Q) ServletConfig Interface & ServletContex Interfaces
ServletConfig à ServletConfig object is used to obtain configuration data when it is loaded. There can be multiple ServletConfig objects in a single web application.
            This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.

Ex:-
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
</servlet>
</web-app>
--------------------------------------
public void init()
{
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverclassname");
String dbURL = config.getInitParameter("dburl");
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(dbURL,username,password);
}

ServletContextà ServletContext is also called application object. ServletContext is used to obtain information about environment on which a servlet is running.
There is one instance object of the ServletContext interface associated with each Web application deployed into a container. In cases where the container is distributed over many virtual machines, a Web application will have an instance of the ServletContext for each JVM.

Servlet Context is a grouping under which related servlets run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.

Q) How to add application scope in Servlets?
A) In Servlets Application is nothing but ServletContext Scope.
ServletContext appContext = servletConfig.getServletContext();
appContext.setAttribute(paramName, req.getParameter(paramName));
            appContext.getAttribute(paramName);

Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be used instead of of Session bean?
A) HttpSession is used to maintain the state of a client in webservers, which are based on Http protocol. Where as Stateful Session bean is a type of bean, which can also maintain the state of the client in Application servers, based on RMI-IIOP.

Q) Can we store objects in a session?
A) session.setAttribute("productIdsInCart",productIdsInCart);
     session.removeAttribute("productIdsInCart");

Q) Servlet Listeners

(i) ServletContextListener
void contextDestroyed (ServletContextEvent sce)
void contextInitialized (ServletContextEvent sce) 
Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

(ii) ServletContextAttributeListener (I)
void attributeAdded (ServletContextAttributeEvent scab)
void attributeRemoved (ServletContextAttributeEvent scab)
void attributeReplaced (ServletContextAttributeEvent scab)
            Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

Q) HttpListeners

(i) HttpSessionListener (I)
public void sessionCreated(HttpSessionEvent event)
public void sessionDestroyed(HttpSessionEvent event)
            Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

(ii) HttpSessionActivationListener (I)
public void sessionWillPassivate(HttpSessionEvent se)
public void sessionDidActivate(HttpSessionEvent se)
Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated.

(iii) HttpSessionAttributeListener (I)
public void attributeAdded(HttpSessionBindingEvent se)
public void attributeRemoved(HttpSessionBindingEvent se)
public void attributeReplaced(HttpSessionBindingEvent se)
This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application.

(iv) HttpSession Binding Listener (** If session will expire how to get the values)
Some objects may wish to perform an action when they are bound (or) unbound from a session. For example, a database connection may begin a transaction when bound to a session and end the transaction when unbound. Any object that implements the javax.servlet.http.HttpSessionBindingListener interface is notified when it is bound (or) unbound from a session. The interface declares two methods, valueBound() and valueUnbound(), that must be implemented:

Methods: -
public void HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)
public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)

valueBound() à method is called when the listener is bound into a session
valueUnbound() à is called when the listener is unbound from a session.
The javax.servlet.http.HttpSessionBindingEvent argument provides access to the name under which the object is being bound (or unbound) with the getName() method:

public String HttpSessionBindingEvent.getName()

The HttpSessionBindingEvent object also provides access to the HttpSession object to which the listener is being bound (or unbound) with getSession() :

public HttpSession HttpSessionBindingEvent.getSession()

=========
public class SessionBindings extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter ();
    HttpSession session = req.getSession(true);
    session.putValue("bindings.listener",
                     new CustomBindingListener(getServletContext()));    // Add a CustomBindingListener
  }
}
=============
class CustomBindingListener implements HttpSessionBindingListener
{
  ServletContext context;

  public CustomBindingListener(ServletContext context) {
    this.context = context;
  }

  public void valueBound(HttpSessionBindingEvent event) {
    context.log("BOUND as " + event.getName() + " to " + event.getSession().getId());
  }

  public void valueUnbound(HttpSessionBindingEvent event) {
    context.log("UNBOUND as " + event.getName() + " from " + event.getSession().getId());
  }
}

Q) Filter
Filter is an object that intercepts a message between a data source and a data destination, and then filters the data being passed between them. It acts as a guard, preventing undesired information from being transmitted from one point to another.

When a servlet container receives a request for a resource, it checks whether a filter is associated with this resource. If a filter is associated with the resource, the servlet container routes the request to the filter instead of routing it to the resource. The filter, after processing the request, does one of three things:
• It generates the response itself and returns it to the client.
• It passes on the request (modified or unmodified) to the next filter in the chain
• It routes the request to a different resource.

Examples of Filtering Components
• Authentication filters       • Logging and auditing filters • Image conversion filters • Data compression filters
• Encryption filters            • Tokenizing filters                 • Filters that trigger resource access events
• MIME-type chain filters               • Caching filters                      • XSL/T filters that transform XML content              

The javax.servlet.Filter interface defines three methods:
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)
public FilterConfig getFilterConfig()
public void setFilterConfig (FilterConfig filterConfig)
Ex:-
public class SimpleFilter implements Filter
{
  private FilterConfig filterConfig;
  public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)
  {
    try
    {
          chain.doFilter (request, response); // for Filter Chain
    } catch (IOException io) {
      System.out.println ("IOException raised in SimpleFilter");
    }
  }

  public FilterConfig getFilterConfig()
  {
    return this.filterConfig;
  }

  public void setFilterConfig (FilterConfig filterConfig)
  {
    this.filterConfig = filterConfig;
  }
}

Filter and the RequestDispatcher
version 2.4 of the Java Servlet specification is the ability to configure filters to be invoked under request dispatcher forward() and include() calls. By using the new <dispatcher>INCLUDE / FORWARD</dispatcher> element in the deployment descriptor,

Q) Are Servlets multithread?
A) Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread of your servlet runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance.

Q) What happens to System.out & System.err output in a Servlet?
A) System.out goes to 'client side' and is seen in browser, while System.err goes to 'server side' and is visible in error logs and/or on console.

Q) Session Tracking
            Session tracking is the capability of the server to maintain the single client sequential list.

Q) Servlet chaining
            Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest

Servlet Aliasing à allow you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain open your browser and give the alias name in URL.

HttpRequestà construct a URL string and append a comma delimited list of servlets to the end.

Q) HttpTunnelling
            Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.

Q) Diff CGI & Servlet
à Servlet is thread based but CGI is process based.
à CGI allow separate process for every client request, CGI is platform dependent and servlet is platform independent.

Q) Diff GET & POST
à GET & POST are used to process request and response of a client.  
à GET method is the part of URL, we send less amount of data through GET. The amount of information limited is 240-255 characters (or 1kb in length).
à Using POST we can send large amount of data through hidden fields.
à Get is to get the posted html data, POST is to post the html data.

Q) Diff Http & Generic Servlet
à HttpServlet class extends Generic servlet , so Generic servlet is parent and HttpServlet is child.
à Generic is from  javax.servlet package, HttpServlet is from javax.servlet.Http package.
à Http implements all Http protocols, Generic servlet will implements all networking protocol
à Http is stateless protocol, which mean each request is independent of previous one, In generic we cannot maintain the state of next page only main state of current page.
à A protocol is said to be stateless if it has n memory of prior connection.
à Http servlet extra functionality is capable of retrieving Http header information.
à Http servlet can override doGet(), doDelete(), doGet(), doPost(), doTrace(), generic servlet will override Service() method only.

Q) Can I catch servlet exception and give my own error message? (or) custom error pages?
A) Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page.

RequestDispatcher dispatcher = null;
request.getRequestDispatcher(/err/SQL.jsp);
try {
 // SQL operation
}
catch (SQLException se) {
dispatcher.forward(request, response);
}       

Web.xml
<error-page>
  <error-code>
    HTTP error code (404)
  <error-code>
  <exception-type>
    java.lang.RuntimeException
  </exception-type>
  <location>
    /err/RuntimeException.jsp
  </location>
</error-page>

Q) How many ways we can instantiate a class?
A) Class.forName().newInstance() and new keyword

Q) Client pull & Server push?
 Client pull
Client pull is similar to redirection, with one major difference: the browser actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. It's called client pull because the client is responsible for pulling the content from the next page.
Client pull information is sent to the client using the Refresh HTTP header. This header's value specifies the number of seconds to display the page before pulling the next one, and it optionally includes a URL string that specifies the URL from which to pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh", "3");
And here's a call that tells the client to display Netscape's home page after the three seconds:
setHeader("Refresh", "3; URL=http://home.netscape.com");

Server push
Server push because the server sends, or pushes, a sequence of response pages to the client. With server push, the socket connection between the client and the server remains open until the last page has been sent.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">

Q) How can a servlet refresh automatically if some new data has entered the database?
A) You can use client side refresh are server push

Q) How can i upload File using a Servlet? 
    <FORM ENCTYPE="multipart/form-data" method=post action="/utils/FileUploadServlet">
       <INPUT TYPE="file" NAME="currentfilename">
       <INPUT TYPE="submit" VALUE="upload">
   </FORM>

Q) Session Tracking techniques
    
(i) URL Rewriting
(ii) Hidden form Field
(iii) Persistence Cookies
(iv) Session Tracking API
(v) User Authorization

URL Rewriting
URL rewriting is a technique in which the requested URL is modified with the session id.
URL rewriting is another way to support anonymous session tracking. With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123   added parameter

Hidden form Field
            Hidden form fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:

<FORM ACTION="/servlet/MovieFinder" METHOD="POST">
   <INPUT TYPE=hidden NAME="zip" VALUE="94040">
   <INPUT TYPE=hidden NAME="level" VALUE="expert">
</FORM>
In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.

Persistence Cookie 
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.

Sending cookies from a servlet

Cookie cookie = new Cookie ("ID", "123");
res.addCookie (cookie);

A servlet retrieves cookies by calling the getCookies () method of HttpServlet- Request:
public Cookie[] HttpServletRequest.getCookies()
This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:

Reading browser cookies from a Servlet

Cookie [] cookies = req. getCookies();
if (cookies != null) {
  for (int i = 0; i < cookies.length; i++) {
    String name = cookies [i]. getName ();
    String value = cookies [i]. getValue();
  }
}

Deleting the Cookies
<%
     Cookie killMyCookie = new Cookie("mycookie", null);
     killMyCookie.setMaxAge(0);
     killMyCookie.setPath("/");
     response.addCookie(killMyCookie);
%>

You can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method:
à Zero means to delete the cookie
à + value is the maximum number of seconds the cookie will live, before it expires
à - value means the cookie will not be stored beyond this browser session (deleted on browser close)

Session Tracking API
In Java the javax.servlet.http.HttpSession API handles many of the details of session tracking. It allows a session object to be created for each user session, then allows for values to be stored and retrieved for each session. A session object is created through the HttpServletRequest using the getSession() method:

HttpSession session = request.getSession(true);

This will return the session for this user or create one if one does not already exist. Values can be stored for a user session using the HttpSession method putValue():

session.putValue("valueName", valueObject);

Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames(). Values can also be removed using removeValue(String valueName)

User Authorization
            Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.

Q) Retrieving query parameters names?
  Enumeration params = request.getParameterNames();
  String paramName = null;
  String[] paramValues = null;

    while (params.hasMoreElements()) {
     paramName = (String) params.nextElement();
     paramValues = request.getParameterValues(paramName);
     System.out.println("\nParameter name is " + paramName);
        for (int i = 0; i < paramValues.length; i++) {
          System.out.println(", value " + i + " is " +
          paramValues[i].toString());
    }
  }

Q) Session
Session is a persistence network connection between client and server that facilitate the exchange of information between client and server. The container generates a session ID, when you create a session the server saves the session ID on the clients machine as a cookie. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time.
           
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length (Identifier), which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.

// If “True” means creating a session if session is not there
// if “False” means session is not created should one does not exist
HttpSession session = req.getSession(true);
session.putValue ("MyIdentifier1", count1);  // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);  
session.getValue(MyIdentifier1); // Prints value of Count
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object

Invalidating a Session
There are 6 different ways to invalidate the session.
1 à Httpsession.setMaxInactiveIntervel(int sec)
2 à Session will automatically expire after a certain time of inactivity
3 à User closes browser window, notice that the session will time out rather than directly triggering session invalidate.
4 à calling invalidate()
5 à if server cashes
6 à put <session-timeout> in web.xml

Q) Cookie advantages & Disadvantages
Advantagesà Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id.
Disadvantageà The biggest problem with cookies is that browser do not always accept cookies. Some times browser does not accept cookies. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. It cannot work if the security level set too high in browser. Cookies are stored in a plain text format so every one can view and modify them. We can put maximum 300 cookies for entire application.

Q) Advantages of Sessions over Cookies & URLRewriting?
à Sessions are more secure and fast because they are stored at server side. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side.
à Cookies are store at client side so some clients may disable cookies so we may not sure that the cookies which we are maintaining may work or not, if cookies are disable also we can maintain sessions using URLRewriting.
à In URLRewriting we cannot maintain large data because it leads to network traffic and access may be become slow. Where in sessions will not maintain the data which we have to maintain instead we will maintain only the session id.

Q) If the cookies at client side are disabled then session don't work, in this case how can we proceed?
A) 1. (from servlet) write the next page with a hidden field containing a unique ID that serves as "session ID". So next time when the user clicks submit, you can retrieve the hidden field.
    2. If you use applet, you may avoid "view source" (so that people can't see the hidden field). Your applet reads back an ID from the servlet and use that from then on to make further requests
 Q) How to confirm that user's browser accepted the Cookie?
A) There's no direct API to directly verify that user's browser accepted the cookie. But the quick alternative would be, after sending the required data to the users browser, redirect the response to a different Servlet which would try to read back the cookie. If this Servlet is able to read back the cookie, then it was successfully saved, else user had disabled the option to accept cookies. 

Q) Diff between Multiple Instances of Browser and Multiple Windows? How does this affect Sessions?
A) àFrom the current Browser window, if we open a new Window, then it referred to as Multiple Windows. Sessions properties are maintained across all these windows, even though they are operating in multiple windows.
à Instead, if we open a new Browser, by either double clicking on the Browser Shortcut then we are creating a new Instance of the Browser. This is referred to as Multiple Instances of Browser. Here each Browser window is considered as different client. So Sessions are not maintained across these windows.

Q) encodeURL & encodeRedirectURL
            These are methods of HttpResponse object,  “encodeURL” is for normal links inside your HTML pages, “encodeRedirectURL” is for a link your passing to response.sendRedirect().

Q) SingleThread model
            SingleThreadModel is a tag interface with no methods. In this model no two threads will execute concurrently the service method of the servlet, to accomplish this each thread uses a free servlet instance from the servlet pool. So any servlet implementing this can be considered thread safe and it is not required synchronize access to its variables.
(or)
If a servlet implements this interface, the server ensures that each instance of the servlet handles only one service request at a time. Servers implement this functionality by maintaining a pool of servlet instances and dispatching incoming requests to free servlets within the pool. SingleThreadModel provides easy thread safety, but at the cost of increased resource requirements as more servlet instances are loaded at any given time.

public interface SingleThreadModel {
}

figure

Q) Request Headers
User-agent: - Gives the information about client software, browser name, version and information about the machine on which it is running.
request.getHeader(“user-agent”);

Q) Why do you need both GET & POST methods in servlets?
A) A single servlet can be called from different HTML pages, so different method calls can be possible.

Q) Servlet output - to - another Servlet? Inter-servlet communication?
A) As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including
Request Dispatching
HTTP Redirect
Servlet Chaining
   
Servlet1
     ServletContext sc = getServletContext();
     RequestDispatcher rd = sc.getRequestDispatcher (“/../srevlet2”) ;
     rd.forward(req, res);
   
Servlet2

Public void service(servletRequest req, servletResponse res)
{
     ServletContext sc = getServletContext();
     RequestDispatcher rd = sc.getRequestDispatcher (“/../srevlet1”) ;
     rd.include(req, res);
}

Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.

Ex:- ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward("NextServlet") ;
You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.

There are some Servlet engine specific configurations for servlet chaining.

Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object.

Ex:- TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); otherServletDetails= Test.getServletDetails();

You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls.

Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet.

Q) Servlet – to- JSP/Servlet communicate? (or) How Servlet invoke a JSP page?
    public void doPost(HttpServletRequest req,
                                   HttpServletResponse res){
    Try{
            govi.FormBean f = new govi.formBean();
             f.setName(req.getParameter(“name”));
             f.setAdress(req.getParameter(“addr”));
             f.setPersonalizationInfo(info);
             req.setAttribute(“fBean”,f);
             getServletConfig().getServletContext().getRequestDispatcher(“/jsp/Bean1.jsp”).forward(req, res);
       } catch(Exception ex);
}
}

The jsp page Bean1.jsp can then process fBean,

<jsp:useBean id=”fBean” class=”govi.formBean” scope=”request” />
<jsp:getProprety name=”fBean” property=”name” />
<jsp:getProprety name=”fBean” property=”addr” />
------------------------------------------------------------ (Or) -----------------------------------------------------------------
You can invoke a JSP page from a servlet through functionality of the standard javax.servlet.RequestDispatcher interface. Complete the following steps in your code to use this mechanism:

1) Get a servlet context instance from the servlet instance:
ServletContext sc = this.getServletContext();

2) Get a request dispatcher from the servlet context instance, specifying the page-relative or application-relative path of the target JSP page as input to the getRequestDispatcher() method:
RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");

Prior to or during this step, you can optionally make data available to the JSP page through attributes of the HTTP request object. See "Passing Data Between a JSP Page and a Servlet" below for information.

3) Invoke the include() or forward() method of the request dispatcher, specifying the HTTP request and response objects as arguments.

rd.include(request, response); / rd.forward(request, response);

The functionality of these methods is similar to that of jsp:include and jsp:forward actions. The include() method only temporarily transfers control; execution returns to the invoking servlet afterward.
Note that the forward() method clears the output buffer.

Q) context.getRequestDispatcher()
     request.getRequestDispatcher()
     context.getNamedDispatcher()

1) ServletContext.getRequestDispatcher( / )                     —> You must use Absolute paths, it can extend outside current servlet context.

2) ServletRequest.getRequestDispatcher(Relative Path)  —> The path may be Relative, but cannot extend outside current servlet context, the URL in the address bar doesn’t change. The client looses path information when it receives a forwarded request.

3) ServletRequest.getNamedDispatcher(String name)     —> This name is the name of the servlet for which a dispatcher is requested, and is in the web.xml file

Ex :-
public class ServletToServlet extends HttpServlet
{
  public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    try {
          getServletConfig()
         .getServletContext().getRequestDispatcher("/HelloWorldExample").forward(request, response);
    } catch (Exception ex) {
      ex.printStackTrace ();
    }
  }
}

 RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
if (dispatcher == null)
{
  out.println(path + " not available");
  return;
} else
{
  dispatcher.include(request, response);
}

Q) Different cases for using sendRedirect() vs. getRequestDispatcher() / getNamedDispatcher?
à When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher (or) getNamedDispatcher.
à If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.

Q) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?
A) You can bind this information to a context that is accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory.

Q) How can I share data between two different web applications?
A) Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications.

Q) How do servlets handle multiple simultaneous requests?
A) The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

Q) How do i get the name of the currently executing script?
A) req.getRequestURI() / req.getServletPath().  The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info.
  URL
GetRequestURI
servlets/HelloServlet/jdata/userinfo
GetServletPath
servlets/HelloServlet/
GetPathInfo
/jdata/userinfo
GetQueryString
pagetype=s3&pagenum=4

Q) How can i stress test my Servlets?
A) following products to stress test your Servlets.
Q) Connection pool class
public class ConnectionPool {
  private Hashtable connections;
  private int increment;
  private String dbURL, user, password;
 
  public ConnectionPool(String dbURL, String user, String password, String driverClassName,
int initialConnections, int increment) throws SQLException, ClassNotFoundException {

    Class.forName(driverClassName);
    this.dbURL = dbURL;
    this.user = user;
    this.password = password;
    this.increment = increment;

    connections = new Hashtable();

    // Put our pool of Connections in the Hashtable
    // The FALSE value indicates they're unused
    for(int i = 0; i < initialConnections; i++) {
      connections.put(DriverManager.getConnection(dbURL, user, password), Boolean.FALSE);
    }
  }

  public Connection getConnection() throws SQLException {
    Connection con = null;

    Enumeration cons = connections.keys();

    synchronized (connnections) {
      while(cons.hasMoreElements()) {
        con = (Connection)cons.nextElement();

        Boolean b = (Boolean)connections.get(con);
        if (b == Boolean.FALSE) {
          // So we found an unused connection. Test its integrity with a quick setAutoCommit(true) call.
          // For production use, more testing should be performed, such as executing a simple query.
          try {
            con.setAutoCommit(true);
          }
          catch(SQLException e) {
            // Problem with the connection, replace it.
            con = DriverManager.getConnection(dbURL, user, password);
          }
          // Update the Hashtable to show this one's taken
          connections.put(con, Boolean.TRUE);
          return con;
        }
      }
    }
 
    // If we get here, there were no free connections.
    // We've got to make more.
    for(int i = 0; i < increment; i++) {
      connections.put(DriverManager.getConnection(dbURL, user, password),
                      Boolean.FALSE);
    }                  

    // Recurse to get one of the new connections.
    return getConnection();
  }

  public void returnConnection(Connection returned) {
    Connection con;
    Enumeration cons = connections.keys();
    while (cons.hasMoreElements()) {
      con = (Connection)cons.nextElement();
      if (con == returned) {
        connections.put(con, Boolean.FALSE);
        break;
      }
    }
  }
}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email