Thursday, October 24, 2013

Basic Servlet Interview Question Answers

In this post, I'm gonna provide basic Servlet concepts with few diagram, so it will be easy to understood and remember. I hope you like these exclusive question-answers and if you like it please share or comment !

  1. What does your Web Server do?
    In simple term, " A web server takes a client request and gives something back to client".
    A web browser lets a user request a resource. The Web server get the request, find the resources, and returns something to the user. Resources can be HTML page, a picture, a sound file and even pdf file.
  2. What is 404 Not Found error?
    When user or web browser ask a resources, unless the thing isn't there or at least it's not where server is expecting it to be then you will get 404 error.
  3. What does web client do?
    Simply to say, "A web client lets the user request something on the server, and shows the user the result of the request".
    Client can be human user or the browser application. Generally, we don't care whether we are talking about human user or the browser app.
  4. How Client and Server talk to each other?
    In order to communicate, they must share a common language. On the web, clients and servers must speak HTTP and browsers must know HTML.
    HTML : tell the browser how to display content to the user.
    HTTP : is the protocol clients and servers use on the web to communicate.
    The server uses the HTTP to send HTML to the client.
  5. What is HTTP protocol?
    HTTP runs on top of TCP/IP.
    TCP is responsible for making sure that file send from one network to another node ends up in a complete file at the destination, even though file split into pieces when it is sent.
    IP is the underlying protocol that moves/routes the pieces from one host to another on their way to the destination.
    HTTP is another protocol that has web-specific features, but it depends on TCP/IP to get the complete request and response from one place to another.

  6. What is the structure of HTTP conversation?
    It's a simple Request/Response sequence; a browser requests and a server response.

    Key elements of request stream :
    HTTP method - action to be performed
    The page to access ( URL )

    Key elements of response stream :
    A status code like 404 etc.
    Content-type like text, picture etc
    The actual content like HTML, image etc

  7. What is in request or what we send in a request?
    First thing you will find is a HTTP method name. These methods tell the server the kind of request that's is being made and how the rest of the message will be formatted. The HTTP protocol has several methods, but we here discuss only the basic ones GET and POST.
  8. What is in response or what server send in a response?
    An HTTP response contain HTML. HTTP adds header information to the top of whatever content is in the response. The HTML browser uses the header info to process the HTML page.
    When the browser finds the opening html tag it goes into HTML -rendering and display the page to the user.
    when the browser get to an image tag, it generate another HTTP request.
  9. What is GET and POST methods?
    GET is a simplest HTTP method, and its main job in life is to ask the server to get a  resources and send it back. The resources can be image, sound file, pdf etc.
    It's also true that amount of characters in a GET is really limited.
    The data send with the GET is appended to the URL.
    POST is more powerful request. It's like GET ++ . With POST, you can request something and at the same time send form data to the server.
  10. Difference between GET and POST?
    1. GET is a safe method (idempotent) where POST is non-idempotent method
    2. We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.
    3. GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.
    4. GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.
    5. Hyperlinks in a page uses GET method.
  11. What is the Structure of HTTP GET request?

  12. What is the Structure of HTTP POST request?

  13. What is MIME type?
    In response header, content-type header's value is known as a MIME type. The MIME type tell the browser what kind of data the browser is going to receive so that the browser will know how to render it.
    Note : MIME type value relates to HTTP request's "Accept" header.
  14. What is the structure of HTTP response?

  15. What is URL and it's format?
    Uniform Resources Locators. Every resources on the web  has it's own unique address, in the URL format.

    http:// Tells the server which communications protocol will be used. The unique name of the physical server you're looking for. This name maps to unique IP address
    80 This part of URL is optional.
    /2013/08/  The path to the location on the server, of the resources being requested.
    garbage-collection-in-java.html The name of the content being requested. This could be HTML page, a servlet, an image, PDF, music, video etc
    Optional Query String If this was GET request, the extra info would be appended to the end of the URL, starting with a question "?" mark.
  16. What is a TCP port number?
    A TCP port is just a number. A 16-bit number that identifies a specific software program on the server hardware. The TCP port numbers from 0 to 1023  are reserved for well-known  services.
    Some well known ports :
    FTP : 21
    TELNET : 23
    SMTP : 25
    TIME : 37
    HTTPS : 443
    POP3 : 110
    HTTP : 80
  17. What two things web server alone can't do?
    First, it can't serve dynamic content. The web server application serves only static web pages, but a separate helper application (servlets) that the web server can communicate with can build non-static, just-in-time pages.
    Secondly, it can't save data on the server.
  18. What is a servlet?
    Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
  19. What is difference between PrintWriter and ServletOutputStream?
    PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.
    We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

  20. What is SingleThreadModel interface?
    SingleThreadModel interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used
  21. Basic steps of request and response flow?
    The user type the URL.
    The browser create an HTTP get request as you seen above diagram.
    The HTTP GET is sent to the server.
    The server find the page.
    Then server generate the response.
    The HTTP response sent to the browser.
    The browser render the page.
    User see the result on the browser.
  22. What is a container?
    Servlets don't have main method. They are under the control of another Java application called a container. For instance, Tomcat.
  23. How Container and Servlets works?
    When your web server application like apache gets a request for a servlet as opposed to a static HTML page, the server hands the request not to the servlet itself, but to the container in which servlet is deployed. It's the container that give servlet the HTTP request and response and it's the container that calls the servlet methods like doGet() and doPost().
  24. What is the advantages of Container?
    It's the container that help you to concentrate on business logic instead of worrying about code for threading, security and networking.
    Container gives you following benefits:
    Communication support : You don't have to build a server socket, listen to port etc for your servlets to talk to your web server.
    Lifecycle Management : It control the life and death of your servlets. It takes care of loading the classes, instantiating and initializing the methods, invoking the servlets methods etc.
    Multithreading support : The container automatically creates a new java thread for every servlet request it receives.
    Declarative Security : With the help of XML deployment descriptor you can configure security without having to hard code it in your sevlet. The same thing can be done with the help of annotations on servlet 3.0+.
    JSP support : Container take care of translating JSP code into real java.
  25. How container handles the a request?
    1. When user clicks on the URL to a sevlet instead of a static page.
    2. The container sees the request is for a servlet, so the container creates 2 objects:
    3. The container finds the correct servlet based on the URL in the request, creates or allocated a thread for that request and passes the request and response object to the servlet thread.
    4. The container calls the service() method. Depending on the type of request, the service method call the doGet() or doPost() method.
    5. The doGet() method generate the page and stuffs the page into response object. The container still has a reference to the response object.
    6. The thread completes, the container convert the response object into HTTP response, sent it back to the client, the delete the request and response objects.
  26. How container found the servlet?
    The URL that comes in as part of the request from the client is mapped to a specific servlet on the server.
    A servlet can have THREE names.
    1. Actual file name : The developer servlet class has a fully qualified name that includes both the class name and package name. The servlet class file has a real path and file name, depending on where the package directory structure lives on the server.
    2. Deployer-known secret internal name : The deployer can create a name that's known only to the deployer and others in operational environment. This name is fake name, made just for the deplyoment of the servlet.
    3. Client -known URL name : The client sees a URL for the servlet, but doesn't really know that servlet name maps to real directories and files back to the server.

    We use deployment descriptor to map URL to servlets.
  27. How to declare URL mapping to servlet?
    Basically, two DD elements  are used for URL mapping.
    1. <servlet> : this maps internal name to fully qualified class name
    2. <servlet-mapping> : this maps internal name to public name.


  28. What are the benefits of DD ( deployment descriptor )? 
    Minimize touching source code.
    Fine tune your application, even if you don't have the code.
    Lets you application to adapt different resources like databases without compiling and test any code.
    Easier to maintain dynamic security like access control lists.
    Let Non-programmers to modify and deploy your web applications
  29. What is MVC and what it does?
    Application is structured in 3 layers:
    Model : containing all data and operations, implemented as java classes
    View : create various presentations, implemented as JSP
    Controller: receive requests, update model and delegating to views, implemented as single servlet.

    The essence of MVC is that you separate the business logic from presentation, but put something between them so that the business logic can stand on its own as reusable class, and doesn't have to know anything about the view.
  30. How MVC use in Servlet and JSP?
    Controller (servlet) : Takes user input from the request and figures out what is means to model. Tell the model to update itself and make the new model state available for JSP (view)
    View : Responsible for the presentation. It gets the state of the model from the controller not directly. It's also the part that gets the user input that goes back to the controller.
    Model : Hold the real business logic and state.It know the rules for getting and updating the state. It's the only part of the system that talks to databases.

  31. Servlet Life cycle methods?
    The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.
    1. If an instance of the servlet does not exist, the web container
        Creates an instance of the servlet class.
    2. Initializes the servlet instance by calling the init method. Initialization is covered in Creating and Initializing a Servlet.
    If it needs to remove the servlet, the container finalizes the servlet by calling the servlet’s destroy method. For more information, see Finalizing a Servlet.

  32. How request is handle by Thread?
    You might hear that "Each instance of the servlet.." but that's just wrong.
    There are not multiple instance of any servlet class, except in one special case called SingleThreadModel.
    The container runs multiple thread to process multiple request to a single servlet.
    Have a look at the picture.

  33. What is ServletConfig object?
    1. There is only one servletConfig object per servlet.
    2. Use it to pass deploy time information to the servlet that you don't want to hard-code into the servlet.
    3. Use it to access the ServletContext.
    4. Parameters are configured in the DD.
  34. What is ServletContextConfig?
    1. There is only one ServletContext per web app.
    2. Use it to access web app parameters.
    3. Use it as a kind of notice board, where you can put up messages application can access.
    4. Use it to get servlet info, including the name and version of the container, and the version of the API that's supported.

  35. Servlet key API's?

  36. What is difference between GenericServlet and HttpServlet?
    GenericServlet is protocol independent implementation of Servlet interface whereas HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that’s why we extend HttpServlet class. HttpServlet class extends GenericServlet and also provide some other methods specific to HTTP protocol
  37. What are the different HTTP request methods?
    GET : Asks to get the resources at the request URL
    POST : Asks the server to accept the body info attached to the request, and give it to the resources at the requested URL.
    HEAD : Asks only for the header part of whatever a GET would return. So it's just like GET, but with no body in the response. Gives you info about the requested URL without  actually getting back the real thing.
    TRACE : Asks for loopback of the request message, so that the client can see what is being received on the other end, for testing.
    PUT :  To put the enclosed info at the requested URL
    DELETE : To delete the resources at the requested URL
    OPTIONS : To list of the HTTP methods to which the resources at the requested URL can respond.
    CONNECT : To connect for the purpose of tunneling.
  38. what is idempotent request?
    Idempotent request means you can do the same thing over and over again, with no unwanted side effects. or A HTTP method is said to be idempotent if it returns the same result every time
    GET,HEAD and PUT are idempotent.
  39. what else you can get besides parameters from request Object?
    1. The client's platform and browser info.
    2. The cookies associated with the request
    3. Session associated with the request
    4. The HTTP method of the request
    5. An input Stream from the request
  40. What is the difference between getServerPort(), getLocalPort() and getRemotePort()?
    getRemotePort() :  means "get the client's port". In other words, the port number on the client from which request was sent. If you are a servlet, remote means client.
    getLocalPort() : means on which port did the request end
    getServerPort() :  means to which port was the request originally sent.
  41. What it Redirect?
    You can choose to have something else handle the response for your request. In that case, you redirect the request to a completely different URL.

    You can use relative URL as the argument to sendDirect(), instead of specifying the whole "http://www....." thing.
    Relative URL come in two flavors: with or without slash (/)

    Imagine client type the following URL and your send redirect method URL does not start with /
    The container build the full URL relative to the original request URL

    But if the argument in send redirect start with /
    The container build the complete URL relative to the web container itself, instead of relative to the original URL of the request.

    You can't do a sendRedirect() after writing the response and it takes a string Not a URL object.
  42. What is request dispatch?
    It means something else on the server do the work while redirect makes the client do the work . So remember, redirect=client and dispatch=server.
    RequestDispatcher has only two methods - forward() and include() and you get requestDispatcher  from the request or from the context.

    ReqeustDispatcher view = request.getRequestDispatcher("result.jsp");
    ReqeustDispatcher view = getServletContext().getRequestDispatcher("/result.jsp"):
  43. Difference between redirect and dispatch?
    When a servlet does a request dispatch, it's like asking a co-worker to take over working with a client . The co-worker ends up responding to client, but the client doesn't care as long as someone responds. The user never knows someone else took over, because URL in the browser bar doesn't change.
    When a servlet does a redirect, it's like asking the client to call someone else instead. In this case, the client is the browser, not the user. The browser makes the new call on the user's behalf, after the originally-requested servlet says," sorry call this guy instead". The user sees the new URL in browser.
  44. What is init Parameters in Servlet?
    Init Parameters are used to define properties that you don't want to hard code in java class. For instance, you email address.



    When the container makes a servlet, it read the DD and creates the name/value pairs for servletConfig. The container never read the inits parameter again! Once the parameters are in servletConfig, they won't be read again until you redeploy the app.

    In servlet code:
  45. What is Context init parameters?
    Contexts init parameters work just like init parameters, except context parameters are available to the entire webapps, not just a single servlet. So that means any servlet and JSP in the app automatically has access to the context init parameters.


    The <context-param> is for the WHOLE app, so its not nested inside an individual <servlet> element.

    In servlet code:
  46. What you do with ServletContext?
    1. Get the init parameters and get/set attributes.
    2. Get info about the servlet/container
    3. Do the request dispatcher.
    4. Write to server log file.

    You can get ServletContext in 2 different ways:
  47. What is ServletContextListener?
    There may a situation where you want to run any code before start of app can serve a client such as db connection. In this case, ServletContextListener come into picture. In ServletContextListener interface, there are two method that are notified when the context is initialized and when the context is destroyed.

    To implement ServletContextListener, write a listener class that implements the ServletContextListener, put it in a WEB-INF/ classes directory and tell the container by putting a <listener> element in the DD.
  48. What are other Listeners and it's purpose?
    ServletContextAtttributeListener : when you want to know if an attribute in a web app context has been added or replaced.
    HttpSessionListener : When you want to know how many concurrent users there are
    ServletRequestListener : When you want to know each time a request comes in, so that you log it.
    ServletRequestAttributeListener : When you want to know when a request attribute  has been added, removed or replaced.
    HttpSessionBindingListener : You have an attribute class and you want objects of this type to be notified when they are bounded or removed from a session.
    HttpSessionAttributeListener : You want to know when session attributes are  added, removed or replaced.
    ServletContextListener : You want to know if a context has been created or destroyed.
    HttpSessionActivationListener : You have an attribute class, and you want objects of this type to be notified when the session to which they're bound is migrating to and from another JVM
  49. Difference between attribute and parameters?

  50. What are the three attribute scope?
    Context Attributes : Everyone in the application has access.
    Not thread safe. To synchronize you must lock on the servlet context
    Session Attributes : Accessible to those with access to specific HttpSession.
    These are also not thread safe.To synchronize you must lock on the HttpSession.
    Request Attributes : Accessible to only those with access specific to ServletRequest.
    The request attributes and local variable are thread safe.
  51. How to maintain client specific state across multiple requests?
    1. Use a stateful session enterprise javabean
    2. Use a database
    3. Use an HttpSession
    An HttpSessionObject can hold conversational state across multiple request from the same client. In other words, it persists for an entire session with a specific client. we can use it to store everything we get back from the client in all the requests the client makes during a session.
  52. How session is maintained?
    The Http protocol uses stateless connections. The client browser takes a connection to the server, send the request, got the response and close the connection. In other words, the connection exists only for a single request/response.

    The idea is simple: on the client first request, the container generates a unique session ID and gives it back to the client with the response. The client sent back the session ID with each subsequent request.
  53. How do the client and container exchange session info?
    The simplest and the most common way is through cookies.

  54. How cookies works?
    You do have to tell the Container that you want to create or use a session, but the container takes care of generating session ID, creating a new cookie object, stuffing the session ID into the cookie, setting the cookie as part of response. And on subsequent requests, the Container gets the session ID from a cookie in the request, matches the session ID with an existing session and associate the session with the current request.

    Sending a session cookie in the response
    HttpSession session =  request.getSession();
    You ask the request for a session, and the container kicks everything else into action. You don't have to do anything.
    You don't make the new HttpSession object yourself.
    You don't generate the session ID.
    You don't make the new Cookie Object.
    You don't associate the session ID with Cookie.
    You don't set the Cookie into the response.
    ALL the cookie works happens behind the scene.

    Getting the session ID from the request
    HttpSession session =  request.getSession();
    It's exactly the same method used to generate the session ID and cookie for the response.
    IF ( request include a session ID cookie )
        find the session matching that ID
    ELSE IF( no session ID cookie OR no current session matching the session ID)
       create a new session.
    ALL the cookie works happens behind the scene.
  55. What happens if client won't accept cookies?
    URL rewriting : something to fall back on.
    If the client won't take cookies, you can use URL rewriting as a backup.  URL rewriting always works.
    Image  a web page where  every link has a little bit of extra info tacked onto the end of the URL. When a user  clicks , the request goes to the container with that extra bit on the end, and the container simply strips off the extra  part of the request URL and  uses it to find the session.

    URL rewriting is automatic... but only if you encode your URL's. You have to run all your URL's through  a method of the  response object  - encodeURL() and the container does everything.
  56. How a session can die?
    It times out
    You call invalidate() on the session object.
    The application goes down.
  57. How to set timeout for a specific session?
    session.setMaxInactiveInterval(20*60); // 20 minutes
  58. What are the different ways of session tracking?
    URL rewriting
    Hidden form fields.
  59. What are the Key milestones for an HttpSession?
    The session is created or destroyed.
    2. Session attributes are added, removed or replaced by other parts of the app.
    3. The session is passivated in one VM and activated in another within  a distributed app.
  60. What happened to ServletContext, ServletConfig and HttpSession in case of clustered environment app is on different JVM?
    Only HttpSession objects and their attributes move from one VM to another.
    There is one ServletContext per VM. There is one ServletConfig per servlet, per VM.
    But there is only one HttpSession object for a given session ID per web app regardless of how many VM's the app is distributed across.

  61. Simple Client and web server interaction?
    1. User click a link in the browser.
    2. Browser formats the request and sends it to the server.
    3. Server find the requested page.
    4. Server formats the response and sends it to the browser.
    5. Browser gets the HTML and renders it into a display for the user.
  62. How the container handles the request?
    1. User clicks a link that has a URL to a servlet instead of a static page.
    2. The Container sees that the request is for a servlet, so the container creates 2 objects: HttpServletResponse and HttpServletRequest.
    3. The container finds the correct servlet based on the URL in the request, creates or allocates a thread for that request and passes the request and response object to the servlet.
    4. The container calls the servlet's service() method. Depending on the type of request, the service() method calls either the doGet() or doPost() method. We assume doGet().
    5. The doGet() method generates the dynamic page and stuffs the page into the response object. Remember, the container stills has a reference to the response object.
    6. The thread completes, the container converts the response object into an Http response, sends it back to the client, then deletes the request and response object.
  63. The story of non-idempotent request?Assume you are purchasing a book from a online website and you have already saved your credit detail.

    1. User hits the checkout button. ( bank details are already submitted).
    2. Browser sends an HTTP request to the server with the book purchase info and user customer ID.
    3. The container sends the request to the checkout servlet for processing.
    4. Servlet debits the user back account.
    5. Servlet update the database i.e, takes the book out of the inventory creates a new shopping cart.
    6. Servlet does not send an obvious response, so User still see the same  shopping cart page and think I better hit the checkout button again.
    7. Browser sends an HTTP request to the server with the book purchase info and customer ID number.
    8. The container sends the request to the checkout servlet for processing.
    9. The servlet does not have a problem with user buying the same book again.
    10. Servlet debits the user bank account second time.
    11. User accept the debit, but charges double than normal price.
    12. When User navigates to the check order status page and sees that user has two orders for the same book.
    13. Boooooom..........
  64. The story of a redirect response?
    1. Client types  a URL into the browser bar.
    2. The request goes to the server/container.
    3. The servlet decides that the request should go to a completely different URL.
    4. The servlet call the sendRedirect(astring) on the response and that's it.
    5. The HTTP response has a status code 301 and location header with a URL as the value.
    6. The browser gets the response, sees the 301 status code, and looks for a location header.
    7. The browser makes a new request using the URL that was the value of a location header in the previous response. The user might notice that the URL in the browser bar changed.
    8. There is nothing unique about the request, even though it happened to be triggered by a redirect.
    9. The server gets the thing at the request URL. Nothing special here.

    10. The Http response is just like any other response,... except is isn't coming from the location the client typed in..
    11. Client surprised to see the new URL....
  65. The Story of a Dispatch response?
    User types a servlet's URL into the browser bar.
    2. The request goes to the server/container.
    3. The servlet decides that the request should go to another part of the web app ( in this case, a JSP)
    4. The servlet call the requestDispatcher and the JSP takes over the response.
    5. The browser gets the response in the usual way, and renders it for the user. Since the browser location bar didn't change, the user does not know that the JSP generated the response.
  66. The story of session migration?
    1. User hit the submit button.
    2. The Load-Balancing server decides to send the request to container A-1 in VM one.
    3. The Container makes a new session, ID#111. The "JSESSIONID" cookie is sent  back to the user in the response.
    4. User select another option and hit the submit button again.
    5. This time, Load-Balancing server decides to send the request to container A-2 in VM two.
    6. The container gets the request, sees the session ID, and realizes that the session is on a different VM. VM one.
    7. The session #111 migrates from VM one to VM two. In other words, it no longer exists on VM one once it moves to VM two. This migration means session was passivated on VM on and activated on VM two.
    8. The container makes a new thread for ServletA, and associate the new request with the recently moves session #111. User new request is sent to the thread, and everybody is happy. User has no idea what happened.
  67. The Role of Web server, Container and Servlet?

    TaskWeb serverContainerServlet
    Create the request and response objectJust before starting the thread
    Call service() methodThen service() method call the doGet() o r doPost()
    Start a new thread to handle requestStart a servlet thread
    Convert a response object to an HTTP response.Generate the HTTP response stream from the data in response object
    Knows HTTPUses it to talk to client browser
    Adds HTML to the responseThe dynamixc content for the client
    Has a reference to the response objectsContainer gives to the servletUses it to print a response.
    Finds URL in the DDTo find the correct servlet for the request
    Deletes the request and respons objectonce the servlet is finished
    Coordinate making dynamic contentKnow how to forward to the containerKnows who to call
    Manages lifecyclesCalls service() method
    Has a name that matches the <servlet-class> element in the DDpublic class whatever

Related Post
120+ Core java interview question answers

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...


  1. This comment has been removed by a blog administrator.

  2. Java Servlet Interview Questions and Answers