Quick Refresh : Servlet


Quick Refresh : Servlet

Question: What is a Servlet?
Answer: Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing.


Question: What are the types of Servlet?
Answer: There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doGet and doPost methods.


Question: Is Servlet a singleton class ?
Answer:A Servlet is not a singleton class.The class itself is not coded to be singleton.But it is a informal specification( without any restriction on Servlet class by making it singleton) that the Servlet container must use only one instance per Servlet declaration.


Question: What are the differences between HttpServlet and Generic Servlets?
Answer: HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

*       doGet, if the servlet supports HTTP GET requests
*       doPost, for HTTP POST requests
*       doPut, for HTTP PUT requests
*       doDelete, for HTTP DELETE requests
*       init and destroy, to manage resources that are held for the life of the servlet
*       getServletInfo, which the servlet uses to provide information about itself

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there's almost no reason to override the doOptions and doTrace methods.
GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.
GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet.
GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.
To write a generic servlet, you need only override the abstract service method.

Question: Differentiate between doGet and doPost method?
Answer: doGet is used when there is requirement of sending data appended to a query string in the URL. The doGet models the GET method of Http and it is used to retrieve the info on the client from some server as a request to it. The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string. GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs.

POST allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can't send a file from the client to the server via GET. POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic

Question: What are methods of HttpServlet?
Answer: The methods of HttpServlet class are :
* doGet() is used to handle the GET, conditional GET, and HEAD requests
* doPost() is used to handle POST requests
* doPut() is used to handle PUT requests
* doDelete() is used to handle DELETE requests
* doOptions() is used to handle the OPTIONS requests and
* doTrace() is used to handle the TRACE requests

Question: What happens when you have no doGet or doPost method in your Servlet class ?
Answer: All Servelts must extends the HttpServlet class.When a request comes the service method of the HttpServlet class is invoked by the container,the service method in turn calls the doGet or doPost method of the user specified Servlet class,If we don't override the doGet or doPost method,the default implementation doGet() and doPost() method is executed defined in the HttpServlet class.Which tells "HTTP Status 405 - HTTP method GET/POSt is not supported by this URL". A typical example of dynamic method dispatch.

Question: What are the lifecycle methods of Servlet?
Answer: The interface javax.servlet.Servlet,  defines the three life-cycle methods. These are:
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps.
1. If an instance of the servlet does not exist, the web container
  * Loads the servlet class.
  * Creates an instance of the servlet class.
  * Initializes the servlet instance by calling the init method. Init method is called only once when first request comes for the servlet.
2. The container invokes the service method, passing request and response objects. service method is called for each request.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.

Question: Who is responsible to create the object of servlet?
Answer: The web container.

Question: How many objects of a servlet is created?
Answer: only one.

Question:  What are the objects that are received when a servlets accepts call from client?
Answer: The objects are ServeltRequest  and ServletResponse . The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client.

Question: What are the type of protocols supported by HttpServlet?
Answer: It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

Question: What are the directory Structure of Web Application?
Answer: Web component follows the standard directory structure defined in the J2EE specification.

Directory Structure of Web Component     
 /     
   index.htm, JSP, Images etc..     
  Web-inf
        web.xml
        classes
          servlet classes
        lib
          jar files
Question: What is the possible case/situation when a Servlet's destroy() method is called,other than the server restart ?
Answer: The Servlet engine may call the destroy() method of Servlet when the container encounters the Servlet is changed, a typical case of hot deployment. In that case the container calls the destroy method and then reloads the Servlet's class, reconstructs and then initializes it.

Question: What is ServletConfig Interface?
An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.
getServletConfig() method of Servlet interface returns the object of ServletConfig.

ServletConfig config=getServletConfig(); //Now we can call the methods of ServletConfig interface

Methods of ServletConfig interface
  • public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  • public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
  • public String getServletName():Returns the name of the servlet.
  • public ServletContext getServletContext():Returns an object of ServletContext.
initialization parameter for a servlet
<web-app> <servlet> ...... <init-param> <param-name>parametername</param-name> <param-value>parametervalue</param-value> </init-param> ...... </servlet> </web-app>

Question: What is ServletContext?
Answer: An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. 
ServletContext is an Interface that also defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param>
Usage of ServletContext Interface

  • The object of ServletContext provides an interface between the container and servlet.
  • The ServletContext object can be used to get configuration information from the web.xml file.
  • The ServletContext object can be used to set, get or remove attribute from the web.xml file.
  • The ServletContext object can be used to provide inter-application communication.
How to get the object of ServletContext interface
  • getServletContext() method of ServletConfig interface returns the object of ServletContext.
  • getServletContext() method of GenericServlet class returns the object of ServletContext.
//We can get the ServletContext object from ServletConfig object ServletContext application=getServletConfig().getServletContext(); //Another convenient way to get the ServletContext object ServletContext application=getServletContext();

Commonly used methods of ServletContext interface
  • public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  • public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters.
  • public void setAttribute(String name,Object object):sets the given object in the application scope.
  • public Object getAttribute(String name):Returns the attribute for the specified name.
  • public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects.
  • public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
initialization parameter in Context scope
<web-app>
 ......
    
  <context-param>
    <param-name>parametername</param-name>
    <param-value>parametervalue</param-value>
  </context-param>
 ......
</web-app>

Question: What is meant by Pre-initialization of Servlet?
Answer: When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-on-startup>
in between the <servlet></servlet> tag.

Question: What mechanisms are used by a Servlet Container to maintain session information?
Answer: Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.

Question: What do you understand by servlet mapping?
Answer: Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

Question: What must be implemented by all Servlets?
Answer: The Servlet Interface must be implemented by all servlets.

Question: What are the differences between Servlet and Applet?
Answer: Servlets are server side components that runs on the Servlet container. Applets are client side components and runs on the web browsers. Servlets have no GUI interface.

Question: What are the uses of Servlets?
Answer: * Servlets are used to process the client request.
   * A Servlet can handle multiple request concurrently and be used to develop high performance system
   * A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

Question: What is a Session?
Answer: A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.

Question: What is HTTPSession Class?
Answer: HttpSession Class provides a way to identify a user across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.

Question: What is Session Tracking? Why do u use Session Tracking in HttpServlet?
Answer: HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.

Question: What is the default session timeout time ?
There is no default session timeout specified in Servlet specification,it is left out to the container.For tomcat it is 30mins.One can always override this value either though DD
<session-config> <session-timeout>600</session-timeout> </session-config>
or programmatically by setMaxInactiveInterval() method on HttpSession  object .If the session timeout is set to -1 the session lifetime extends to infinity i.e. as long as the container is running.

Question: What is Session ID?
Answer: A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.

Question: What  are different types of Session Tracking?
Answer: Mechanism for Session Tracking are:
   a) Cookies
   b) URL rewriting
   c) Hidden form fields
   d) SSL Sessions

a) Cookies: A cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
Cookie works at client side whereas HttpSession works at server side.

javax.servlet.http.Cookie class provides the functionality of using cookies.
Cookie(String name, String value): Constructs a cookie with a specified name and value.
There are given some commonly used methods of the Cookie class.
  • public void setMaxAge(int expiry):Sets the maximum age of the cookie in seconds.
  • public String getName():Returns the name of the cookie. The name cannot be changed after creation.
  • public String getValue():Returns the value of the cookie.
For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:

  • public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
  • public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.
//Creating and adding cookie
Cookie ck=new Cookie("uname",n);//creating cookie object response.addCookie(ck);//adding cookie in the response

//Retriving cookie
Cookie ck[]=request.getCookies(); out.print("Hello "+ck[0].getValue());

Disadvantage of Cookies
  • It will not work if cookie is disabled from the browser.
  • Only textual information can be set in Cookie object.
Advantage of Cookies over URL rewriting:  
Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.
Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not.
In url  rewriting requires large data transfer from and to the server. So, it leads to network traffic and access may be become slow.

b) URL Rewriting: In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting:

  • It will always work whether cookie is disabled or not (browser independent).
  • Extra form submission is not required on each pages.
Disadvantage of URL Rewriting:

  • It will work only with links.
  • It can send Only textual information.
c) Hidden Form: In case of Hidden Form Field an invisible textfield is used for maintaing the state of an user. In 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.
out.print("&lt;input type='hidden' name="uname" value='"+n+"'&gt;");
Advantage of Hidden Form Field: 
  • It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field: 
  • It is maintained at server side. 
  • Extra form submission is required on each pages.
  • Only textual information can be used.
d) HttpSession interface:
In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks:
  • bind objects
  • view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.

// set session attibute
HttpSession session=request.getSession();
session.setAttribute("uname","deepak");

//get session attribute
HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname");

The HttpServletRequest interface provides two methods to get the object of HttpSession:
  • public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  • public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
Commonly used methods of HttpSession interface:
  • public String getId():Returns a string containing the unique identifier value.
  • public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  • public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  • public void invalidate():Invalidates this session then unbinds any objects bound to it.
Question: What is session hijacking?
Answer: If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress.

Question: What is Session Migration?
Answer: Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

Question: How many session  will be created  if the same user uses two different browser window ?
If two different browser instances were used for example : FireFox and IE then two session will be created,But if browser tab is used then a single session will be created.

Question: How you can destroy the session in Servlet?
Answer: You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();

Question: What are the things to be taken care of if the session is configured to be replicable in any container,in clustered environment ?
Answer: The session data will be replicated effortlessly without a developers evolvement ( No specific coding is needed to replicate session data ), but one thing the developer must do, is to make sure the object that is getting shared through session must be Serializable.


Question: What is RequestDispatcher and sendRedirect?
Answer:
RequestDispatcher Interface: The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.This interface can also be used to include the content of antoher resource also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.
  • public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
  • public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP page, or HTML file) in the response.Inline image 2
As you see in the above figure, response of second servlet is sent to the client. Reponse of the first servlet is not displayed to the user.Inline image 1
As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.

The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher.
  • public RequestDispatcher getRequestDispatcher(String resource);
sendRedirect() method:
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It can accept relative URL. This method can work inside and outside the server as it uses the URL bar of the browser.
public void sendRedirect(String URL)throws IOException;
sendRedirect method works at client side, that is why we can send our request to anywhere. We can send our request within and outside the server.

Question: What is Filter and FilterChain?
Filter: A filter is an object that is used to perform filtering tasks such as conversion, log maintain, compression, encryption and decryption, input validation etc. A filter is invoked at the preprocessing and postprocessing of a request. It 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. So it will be easier to maintain the web application.
Filter interface: For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter.
  • public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  • public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain): doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
  • public void destroy():This is invoked only once when filter is taken out of the service.
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:
  • public void doFilter(HttpServletRequest request, HttpServletResponse response):</strong> it passes the control to the next filter or resource.
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.
We can define filter same as servlet. Let's see the elements of filter and filter-mapping.
<web-app> <filter> <filter-name>...</filter-name> <filter-class>...</filter-class> </filter> <filter-mapping> <filter-name>...</filter-name> <url-pattern>...</url-pattern> </filter-mapping> </web-app>

FilterConfig: 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.
There are following 4 methods in the FilterConfig interface.
  • public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  • public String getInitParameter(String parameterName): Returns the parameter value for the specified parameter name.
  • public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter names.
  • public ServletContext getServletContext(): Returns the ServletContext object.

Comments

Popular posts from this blog

Ramoji Film City, Hyderabad, India

Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

Quick Refresh : Hibernate