Thursday, June 18, 2009

Servlet Interview Questions

1) What is the difference between CGI and Servlet?

Traditional CGI(Common Gateway Interface)
  • Traditional CGI creates a heavy weight process to handle each http request.
  • N number of copies of the same traditional CGI programs is copied into memory to serve N number of requests.
Servlet
  • Java ServletServlets a lightweight Java thread to handle each http request.
  • Single copy of a type of servlet but N number of threads (thread sizes can be configured in an application server).


2) What is a Servlet?
  • A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests.

3) What are the two objects a servlet receives when it accepts a call from its client?
  • A “ServletRequest”, which encapsulates client request from the client.
  • A “ServletResponse”, which encapsulates the communication from the servlet back to the client.

4) Explain the life cycle methods of a servlet?
  • The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
  • public void init(ServletConfig config) throws ServletException
  • public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
  • public void destroy()
  • The Web container is responsible for managing the servlet’s life cycle.
  • The Web container creates an instance of the servlet and then the container calls the init() method.
  • At the completion of the init() method the servlet is in ready state to service requests from clients.
  • The container calls the servlet’s service() method for handling each request.
  • Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.

5) What is preinitialization of a servlet?
  • The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
  • 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.
  • 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***.

6) What is the difference between HttpServlet and GenericServlet?
  • Both these classes are abstract but:
GenericServlet
  • A GenericServlet has a service() method to handle requests.
  • All client requests are handled through the service() method. The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request.
HttpServlet
  • The HttpServlet extends GenericServlet and adds support for HTTP protocol based methods like doGet(), doPost(), doHead() etc.
  • HttpServlet also has methods like doHead(), doPut(), doOptions(), doDelete(), and doTrace().Protocol independent. GenericServlet is for servletsthat might not use HTTP (for example FTP service). Protocol dependent

7) Explain ServletContext.
  • A servlet can use ServletContext interface to get information such as initialization parameters for the web application.
  • Every web application has one and only one ServletContext and is accessible to all active resource of that application.

8) What are the ServletContext and ServletConfig objects? What are Servlet environment objects?
ServletConfig
  • The servlet engine implements the ServletConfig interface in order to pass configuration details from the deployment descriptor (web.xml) to a servlet via its init() method.
  • The ServletConfig parameters are for a particularServlet.
  • The parameters are specified in the web.xml(i.e. deployment descriptor). It is created after a servlet is instantiated and it is used to pass initialization information to the servlet.
ServletContext
  • The ServletContext parameters are specified for the entire Web application.
  • The parameters are specified in the web.xml (i.e. deployment descriptor).
  • Servlet context is common to all Servlets. So all Servlets share information through ServletContext.

9) How does an HTTP Servlet handle client requests?
  • All client requests are handled through the service() method.
  • The service method dispatches the request to an appropriate method like doGet(), doPost() etc to handle that request.

10) Cookies: A cookie is a piece of text that a Web server can store on a user’s hard disk. Cookies allow a website to store information on a user’s machine and later retrieve it. These pieces of information are stored as name-value pairs.


11)What is the difference between doGet () and doPost () or GET and POST?

GET or doGet()
  • The request parameters are transmitted as a query string appended to the request. All the parameters get appended to the URL in the address bar. Allows browser bookmarks but not appropriate for transmitting private or sensitive information.
  • http://MyServer/MyServlet?name=paul This is a security risk.
  • GET is not appropriate when large amounts of input data are being transferred. Limited to 1024 characters.
POST or doPost()
  • The request parameters are passed with the body of the request. More secured.
  • In HTML you can specify as follows:
  • POST was intended for form submits where the state of the model and database are expected to change.
  • Since it sends information through a socket back to the server and it won’t show up in the URL address bar, it can send much more information to the server. Unlike doGet(), it is not restricted to sending only textual data. It can also send binary data such as serialized Java objects.

12) HTTP is a stateless protocol, so, how do you maintain state? How do you store user data between requests?
  • The “http protocol” is a stateless request/response based protocol.
  • You can retain the state information between different page requests as follows:
  • HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation.
  • All the servlets can share the same session.
  • The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. In a Java servlet the session can be obtained as follows:
  • HttpSession session = request.getSession(true); //returns a current session or a new session
  • //To put/get a value in/from the session
  • Name name = new Name(“Peter”);
  • session.setAttribute(“Firstname”, name); //session.putValue(…) is deprecated as of 2.2
  • session.getAttribute(“Firstname”);//get a value. session.getValue(…) is deprecated
  • //If a session is no longer required e.g. user has logged out, etc then it can be invalidated.session.invalidate();
  • //you can also set the session inactivity lease period on a per session basissession.setMaxInactiveInterval(300);//resets inactivity period for this session as 5 minutes

13) What is the difference between using getSession(true) and getSession(false) methods?
getSession(true): This method will check whether there is already a session exists for the user. If a sessionexists, it returns that session object. If a session does not already exist then it creates a new session for the user.

getSession(false): This method will check whether there is already a session exists for the user. If a sessionexists, it returns that session object. If a session does not already exist then it returns null.


14) What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
  • 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 accepts relative paths.
  • All path must start with a "/" and are interpreted as relative to current context root.

15) What is the difference between forwarding a request and redirecting a request? Both methods send you to a new resource like Servlet, JSP etc.
redirecting - sendRedirect()
  • Sends a header back to the browser, which contains the name of the resource to be redirected to. The browser will make a fresh request from this header information. Need to provide absolute URL path.
Forward
  • Forward action takes place within the server withoutthe knowledge of the browser. Accepts relative path to the servlet or context root.Has an overhead of extra remote trip but has the advantage of being able to refer to any resource on the same or different domain and also allows book marking of the page. No extra network trip.

16) Explain the directory structure of a web application.
  • The directory structure of a web application consists of two parts.
  • A private directory called WEB-INFA public resource directory which contains public resource folder.
  • WEB-INF folder consists of web.xml classes directory lib directory

17) What is a filter, and how does it work?
  • A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses.
  • Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit.


18) How do you make a Servlet thread safe? What do you need to be concerned about with storing data in Servlet instance fields?
  • A Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method.
  • The multithreading aids efficiency but the servlet code must be coded in a thread safe manner.
  • The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner.
  • There are situations where synchronizing will not give you the expected results and to achieve the expected results you should store your values in a user session or store them as a hidden field values.
  • Having large chunks of code in synchronized blocks in your service or doPost() methods can adversely affect performance and makes the code more complex.Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or nullinterface javax.servlet.SingleThreadedModel.
  • The container will use one of the following approaches to ensure thread safety:Instance pooling: where container maintains a pool of servlets.Sequential processing: where new requests will wait while the current request is being processed.
  • Best practice: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized, used in randomly manner, or shared values can be stored in a session, as hidden fields or in database table. The single threaded model can adversely affect performance and hence has been deprecated in the servlet specification 2.4.

19) Is it possible to share an HttpSession between a Servlet/JSP and EJB?
  • You can pass an HttpSession as a parameter to an EJB method only if all objects in session are serializable.
  • This is because they are “passed-byvalue”and if any values in the HttpSession are altered inside the EJB then it won’t be reflected back to the HttpSession in the Servlet.
  • Even though it is possible to pass an HttpSession object, it is a bad practice in terms of design because you are unnecessarily coupling your presentation tier (i.e. Servlet/JSP) object with your business-tier (i.e. EJB) objects. So rather than passing the whole, large HttpSession create a class (i.e. Plain Old Java Object) that acts as a value object (aka Data Transfer Object) that holds all the data you need to pass back and forth between your presentation tier and business tier. This approach would also be flexible enough to handle a scenario where your EJBs in the business tier need to support a non-http based client like a stand alone Java application or a WAP client.

References:
  1. Java/J2EE Job Interview Companion by Arulkumaran.
  2. http://www.allapplabs.com/index.html
  3. http://www.java-interview.com/index.html

No comments:

Post a Comment