Sunday, August 4, 2013

71 Servlet Interview Questions

Servlets Interview Questions

1. What is the Servlet?
Ans. A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request- response programming model.

2.What are the new features added to Servlet 2.5?
Ans. Following are the changes introduced in Servlet 2.5:
  • A new dependency on J2SE 5.0
  • Support for annotations
  • Loading the class
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications

3. What are the uses of Servlet?
Ans. Typical uses for HTTP Servlets include:
  • Processing and/or storing data submitted by an HTML form.
  • Providing dynamic content, e.g. returning the results of a database query to the client.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

4.What are the advantages of Servlet over CGI?
Ans. Servlets have several advantages over CGI:
  • A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
  • A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications

5. What are the phases of the servlet life cycle?
The life cycle of a servlet consists of the following phases:
  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.
  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

6. Why do we need a constructor in a servlet if we use the init method?
Ans. Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.

7. How the servlet is loaded?
Ans. A servlet can be loaded when:
  • First request is made.
  • Server starts up (auto-load).
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Administrator manually loads.

8. How a Servlet is unloaded?
Ans. A servlet is unloaded when:
  • Server shuts down.
  • Administrator manually unloads.

9. What is Servlet interface?
Ans. The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.

Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

  •  
10.What is the GenericServlet class?
Ans. GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.

11.What's the difference between GenericServlet and HttpServlet?
GenericServlet
HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.
An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers.
The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol.
HttpServlet only supports HTTP and HTTPS protocol.


12.Why is HttpServlet declared abstract?
Ans. The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

13. Can servlet have a constructor ?
Ans. One can definitely have constructor in servlet. Even you can use the constrctor in servlet for initialization purpose, but this type of approach is not so common. You can perform common operations with the constructor as you normally do. The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do. In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

14. What are the types of protocols supported by HttpServlet ?
Ans. It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

15.What is the difference between doGet() and doPost()?

doGet()
doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.
In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)
doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encrypted
Parameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance
doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many times
This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsible
This method does not need to be either safe
8
It allows bookmarks.
It disallows bookmarks.

16.When to use doGet() and when doPost()?
Ans. Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
  • If data is sensitive
  • Data is greater than 1024 characters
  • If your application don't need bookmarks.

17. How do I support both GET and POST from the same Servlet?
Ans. The easy way is, just support POST, then have your doGet method call your doPost method:

 public void doGet(HttpServletRequest request, HttpServletResponse response)

                        throws ServletException, IOException

{

    doPost(request, response);   

}

18.Should I override the service() method?
Ans.We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request. For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

19.How the typical servlet code look like ?

20. What is a servlet context object?
Ans. A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

21.What are the differences between the ServletConfig interface and the ServletContext interface?
ServletConfig
ServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig parameter per servlet.
There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web.xml file
The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.

22.What's the difference between forward() and sendRedirect() methods?
forward()
sendRedirect()
A forward is performed internally by the servlet.
A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
The  browser is completely unaware that it has taken place, so its original URL remains intact.
The browser, in this case, is doing the work and knows that it's making a new request.
Any browser reload of the resulting page will simple repeat the original request, with the original URL
A browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable)
This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Since both resources are part of same context, the original request context is retained
Because this involves a new request, the previous request scope objects, with all of its parameters and attributes are no longer available after a redirect.
(Variables will need to be passed by via the session object).
Forward is marginally faster than redirect.
redirect is marginally slower than a forward, since it requires two browser requests, not one.

23.What is the difference between the include() and forward() methods?
include()
forward()
The RequestDispatcher include() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.
The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored.
The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets.
The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.

24.What's the use of the servlet wrapper classes?
Ans. The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.

25.What is the directory structure of a WAR file?

26.What is a deployment descriptor?
Ans. A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean. The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.

27.What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

ServletRequest.getRequestDispatcher(String path)
ServletContext.getRequestDispatcher(String path)
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are   interpreted as relative to current context root.

28.What is pre-initialization of a servlet?
A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

29.What is the <load-on-startup> element?
Ans. The <load-on-startup> element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The <load-on-startup> element is written in the deployment descriptor as follows:
<servlet>

   <servlet-name>ServletName</servlet-name>

   <servlet-class>ClassName</servlet-class>

   <load-on-startup>1</load-on-startup>

</servlet>
 
30.What is session?
Ans. A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.

31.What is Session Tracking?
Ans. Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

32.What is the need of Session Tracking in web application?
Ans. HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is referred as "state". To keep track of this state we need session tracking.

Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests.

33.What are the types of Session Tracking ?
Ans. Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
  • URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.

  • Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

  • Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.

  • Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.
34. How do I use cookies to store session state on the client?
Ans. In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
  • To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
  • To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest

35. What are some advantages of storing session state in cookies?
  • Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction.
  • For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.

36.What are some disadvantages of storing session state in cookies?
  • Cookies are controlled by programming a low-level API, which is more difficult to implement than some other approaches.
  • All data for a session are kept on the client. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information.
  • Cookies may not be available for many reasons: the user may have disabled them, the browser version may not support them, the browser may be behind a firewall that filters cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and then switching to an alternate client-side session state strategy in cases where cookies aren't available, complicates development and maintenance.
  • Browser instances share cookies, so users cannot have multiple simultaneous sessions.
  • Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the HTTP protocol. Notice that the while package javax.servlet.http supports session management (via class HttpSession), package javax.servlet has no such support.

37. What is URL rewriting?
Ans. URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.

E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
  • URL rewriting works just about everywhere, especially when cookies are turned off.
  • Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
  • Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.

DisAdvantages
  • Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
  • URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
  • URL rewriting does not work well with JSP technology.
  • If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.

38. How can an existing session be invalidated?
Ans. An existing session can be invalidated in the following two ways:
  • Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows:
<session-config>

       <session-timeout>10</session-timeout>

</session-config>
This will set the time for session timeout to be ten minutes.

  • Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
                   public void setMaxInactiveInterval(int interval)

The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.
Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.

39. How can the session in Servlet can be destroyed?
Ans. An existing session can be destroyed in the following two ways:
  • Programatically : Using session.invalidate() method, which makes the container abonden the session on which the method is called.
  • When the server itself is shutdown.

40. A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?
Ans. Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.

41.What is servlet lazy loading?
  • A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
  • The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
  • The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

42. What is Servlet Chaining?
Ans. Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

43. How are filters?
Ans. Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
  • Security checks
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

44.What are the functions of an intercepting filter?
Ans. The functions of an intercepting filter are as follows:
  • It intercepts the request from a client before it reaches the servlet and modifies the request if required.
  • It intercepts the response from the servlet back to the client and modifies the request if required.
  • There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.


45. What are the functions of the Servlet container?
Ans. The functions of the Servlet container are as follows:
  • Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
  • Communication support : It handles the communication between the servlet and the Web server.
  • Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
  • Declarative security : It manages the security inside the XML deployment descriptor file.
  • JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.

46. What is the difference between the getRequestDispatcher(String) and getNamedDispatcher(String) methods in the ServletContext Class?
Ans.
NamedDispatcher :
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

getNamedDispatcher(String) method takes the name of the Servlet as parameter which is declared via Deployment descriptor.

Example: Deployment Descriptor
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>com.example.ServletTest</servlet-class>
</servlet>

RequestDispatcher dispatch = request.getNamedDispatcher("ServletTest");
dispatch.forward(request, response);

Note: A servlet instance can determine its name using servletConfig.getServletName(); This method returns the name of the class that implements the Servlet interface or extends the HttpServlet class.

RequestDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
RequestDispatcher dispatch = request.getRequestDispatcher("/satya");
Here "/satya" represents the url-pattern element value of the servlet class.

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/satya</url-pattern>
</servlet-mapping>

47. What is load-on-startup in servlet ?
Ans. On server startup servlet will be called by the server.
the value 1 in <load-on-startup>1</load-on-startup> specifies the order in which the servlet must be loaded by the server..
if you have 2 servlet you can specify <load-on-startup>2</load-on-startup> for the next servlet
Below is the servlet tag entry in web.xml:
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>util.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

48. Why do servlets have an init method? Can't we make use of the servlet constructor for initialization?
Ans. You can't make use of the constructor because the container calls it and therefore you can't pass any parameters to the constructor. Also at the point the constructor is called the class is not really a Servlet because it doesn't have a reference to the ServletConfig, which provides all the initialisation parameters etc.

Because the servlet container manages the servlet lifecycle, one should never call the constructor, the init and destroy methods.

49. Why can't a container call constructor having parameters?
Ans. As it is the container that manages a servlets lifecycle, you must define a generic way of working for all servlets. You can't use the constructor because otherwise you would have to modify the container to tell him to instantiate this particular servlet.

50. How can I use servlets with protocols other than HTTP, e.g. FTP?
Ans. The javadocs for javax.servlet.Servlet and GenericServlet make it sound as if protocols other than HTTP can be used simply by extending GenericServlet, and implementing the methods that deal with the protocol, much like HttpServlet does for HTTP. That is not the case. The protocol needs to be supported by the servlet engine (which does all the network handling for the servlet), and no servlet engine exists that supports anything other than HTTP(S). Adding a different protocol would be a big project, especially since other protocols don't have the same request/response nature of HTTP. If you find yourself contemplating such a project, post your requirements to the Servlet forum, and a better solution will probably be suggested.

For JSPs, the specification says "Most JSP pages use the HTTP protocol, but other protocols are allowed by this specification.". Since a non-HTTP JSP implementation would depend on a non-HTTP servlet implementation, that too is just a theoretical possibility.

(Note that all of this has nothing to do with a servlet's ability to be a client for other protocols. E.g., by using the JavaMail or Jakarta Commons Net APIs a servlet can access SMTP and FTP servers without problems.)

51. How do I implement security for my web application ?
Ans. The use of HTTPS/SSL can be required by adding the following to the web.xml file:

<security-constraint>
<web-resource-collection>
<web-resource-name>Entire Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>

<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

52. Why IllegalStateException in jsp/servet?
Ans. by attempting to redirect from within the middle of a JSP page you will get IllegalStateException .
For Example
<div>News </div>
<%  if ("not logged in")
response.sendRedirect("login.jsp"); %>
<div>more news</div>

You can avoid this by using return ;
 Example :
<div>News </div>
<%  if ("not logged in")
response.sendRedirect("login.jsp");
return; %>
<div>more news</div>

or
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
            if("client".equals(request.getParameter("user_type"))){
            response.sendRedirect("client-screen.jsp");
            return; // <------- This return statement prevents any further writing to the outputStream
}

//
// Other code that may write to the outputStream....
//

53. When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
Ans. The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
For Example---
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/artadmin</url-pattern>
</servlet-mapping>
if the url in browser is http://localhost:8080/artadmin

then server will call LoginServlet. Based on the above mapping.

54. Request parameter How to find whether a parameter exists in the request object?
Ans. 1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);

55. Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?

Ans. Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet?s service() method to finish.

56. Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?

Ans. Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

57. When we don't write any constructor for the servlet, how does container create an instance of servlet?

Ans. Container creates instance of servlet by calling Class.forName(className).newInstance().

58. Why don't we write a constructor in a servlet?

Ans. Container writes a no argument constructor for our servlet.

59. What is the difference between ServletContext and PageContext?

Ans. ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

60. What's the difference between init() & init(ServletConfig) in genericServlet ?

Ans. init(ServletConfig ):
The default implementation of init(ServletConfig) does some initialization then calls init(). If you use init(ServletConfig) and forget to call super.init(config) at the start of the method then your Servlet will not be initialized correctly.
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
You will get the ServletConfig object.

init():
You can get the ServletConfig using getServletConfig().
A convenience method which can be overridden so that there's no need to call super.init(config).
Instead of overriding init(ServletConfig), simply override this method and it will be called by GenericServlet.init(ServletConfig config). The ServletConfig object can still be retrieved via getServletConfig().

It is BETTER to use init(). If you use init() you have no such worries as calling super.init().

Details :

Before start we have to understand the servlet flow.
For example you have servlet LoginServlet which extends HttpServlet

public class LoginServlet extends HttpServlet{ }

And your HttpServlet internally extends GenericServlet.

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {     
public GenericServlet() { }
public void init() throws ServletException { }
public ServletConfig getServletConfig() { return config; }
public void init(ServletConfig config) throws ServletException {
this.config = config;
init();
}

public abstract void service(ServletRequest servletrequest, ServletResponse servletresponse)
throws ServletException, IOException;
      private transient ServletConfig config; }

Now servlet container flow

Step 1. Loads the servlet class and create instance of the servlet class (LoginServlet).
LoginServlet login = new LoginServlet();

Step 2. Then servlet container create ServletConfig object for that servlet and
Call login.init(ServletConfig);

Case 1 :
If you have overridden init(ServletConfig) method in your servlet then call goes to your
init(ServletConfig) method .

public void init(ServletConfig config) throws ServletException {
       System.out.println("\n**** Initializing LoginServlet Init Servlet ********** \n"); 
       super.init(config);
    }

It will print "Initializing LoginServlet Init Servlet" and call goes to supper class GenericServlet init(ServletConfig) method.

In the GenericServlet init(ServletConfig) method there is code
This.config= config // initialize the Servlet config object and it is available to you.

Case 2 :
If you overridden init() method and not overridden init(ServletConfig) method.
Servlet container call login.init(ServletConfig);

There is no method like init(ServletConfig) in your servlet so call directly goes to super class GenericServlet init(ServletConfig) method.
This.config= config
// initialize the Servlet config object and it is available to you.

You can get the Servlet config object using getServletConfig() method.
Conclusion: It is BETTER to use init(). If you use init() you have no such worries as calling super.init().
If you use init(servletconfig) and forgot to call super.init(config) then servletconfig object will not set and you will not get the servletconfig object.

 

61. Can we override service method in HttpServlet ?

Ans. You can override service method in HttpServlet also.
If you override service method in HttpServlet then call will go to service() method instead of doGet() or doPost() method.

If the jsp form you mentioned
<form name="reg" method="post">
then also call will go to service method of the servlet. Call don't go to doPost() method. you can call doPost() method explicitly from servive() method.
If the jsp form you mentioned
<form name="reg" method="get">
then also call will go to service method of the servlet. Call don't go to doGet() method. you can call doGet () method explicitly from servive() method.

62. How does one choose between overriding the doGet(), doPost(), and service() methods?
Ans. The differences between the doGet() and doPost() methods are that they are called in the HttpServlet that your servlet extends by its service() method when it recieves a GET or a POST request from a HTTP protocol request.
A GET request is a request to get a resource from the server. This is the case of a browser requesting a web page. It is also possible to specify parameters in the request, but the length of the parameters on the whole is limited. This is the case of a form in a web page declared this way in html: <form method="GET"> or <form>.
A POST request is a request to post (to send) form data to a resource on the server. This is the case of of a form in a web page declared this way in html: <form method="POST">. In this case the size of the parameters can be much greater.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are (you must do the parsing yourself).
The HttpServlet instead has doGet() and doPost() methods that get called when a client request is GET or POST. This means that the parsing of the request is done by the servlet: you have the appropriate method called and have convenience methods to read the request parameters.
NOTE: the doGet() and doPost() methods (as well as other HttpServlet methods) are called by the service() method.
Concluding, if you must respond to GET or POST requests made by a HTTP protocol client (usually a browser) don't hesitate to extend HttpServlet and use its convenience methods.
If you must respond to requests made by a client that is not using the HTTP protocol, you must use service().

63. How can my application get to know when a HttpSession is removed?
Ans. Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.

Create an instance of that class and put that instance in HttpSession. 

64. Can we use the constructor, instead of init(), to initialize servlet?
Ans. Yes, of course you can use the constructor instead of init(). 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.

65. How does a servlet communicate with a JSP page?

Ans. In the service method
protected void service(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, java.io.IOException {

User user = (User)request.getSession().getAttribute("user");
                
        String imgId = (String)request.getParameter("imgId");
        String path = request.getContextPath()+"/jsp/addnetwork.jsp";
        
        //do some thing
User user = DAO.getUser(imgId);
request.getSession().setAttribute("user",user);    
         response.sendRedirect(path);

66. How to create and retrieve a multiple selections list in jsp/servlet?

Ans. This is the code to display multiple selections list in jsp.
List medList = DAO.getallMedium(); // this method retun list of Medium objects.
medList list contains list of Medium objects.

Java :
bean class.
public class Medium {
    int medId;
    String medName;
    public int getMedId() {
        return medId;
    }
    public void setMedId(int medId) {
        this.medId = medId;
    }
    public String getMedName() {
        return medName;
    }
    public void setMedName(String medName) {
        this.medName = medName;
    }
}

DAO Clas to retrive mediums in data base.
public static List getMediums(){
        PreparedStatement pStmt = null;
     Connection conn = null;
     boolean success = false;
     ResultSet rs = null;
     List medList = new ArrayList();
    
     try{
         conn = getConnection();
         
         String sql = " select * from MEDIUM ";
         pStmt = conn.prepareStatement(sql);
                  
         rs = pStmt.executeQuery();
         while(rs.next()){
             Medium med = new Medium();
             med.setMedId(rs.getInt("MED_ID"));
             med.setMedName(rs.getString("MEDIUM_NAME"));
             medList.add(med);
             }
  }catch(Exception e){
         e.printStackTrace();
         
     }finally{
         closeConnectionProp(conn,pStmt,rs);
     }
     return medList;
    }

JSP :
<select name="Medium" id="medium" multiple=true>
<option value="0">Choose A Medium</option>

<%
     for(int i=0; i<medList.size();i++){
         Medium med = (Medium)medList.get(i);
     %>
<option value="<%=med.getMedId()%>"><%=med.getMedName()%></option>
<%}%>
</select>

Servlet :
Retrive the multiple selections from jsp
String[] mediums = request.getParameterValues("medium");
for(int i=0;i<mediums.length;i++)
{ System.out.println(mediums[i]); }

67. Why to use the HttpServlet Init method to perform expensive operations that need only be done once?
Ans. Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.

68. When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
Ans. I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML valuators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

69. What is filter? Can filter be used as request or response?
Ans. A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

70. When a client request is sent to the servlet container, how does the container choose .which servlet to invoke?
Ans. The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

71. If a servlet is not properly initialized, what exception may be thrown?
Ans. During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.



1 comment:

anurag singh said...

Thank you so much for posting such great article for Servlet Interview Questions and answers .