Clouds
Home

J2EE Overview

J2EE Servlet 1

J2EE Servlet 2

J2EE JSP

J2EE JDBC

J2EE JNDI LDAP

J2EE RMI

J2EE EJB

J2EE JMS

J2EE XML

J2EE STRUTS

J2EE SERVERS

J2EE Best Practices

J2EE Logging

J2EE Testing

J2EE Deployment

J2EE Development Process

Servlet Interview Questions - Part 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.

Java Servlet

Spawns 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).A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests concurrently forwarded through the server and the web container. The web browser establishes a socket connection to the host server in the URL , and sends the HTTP request. Servlets can forward requests to other servers and servlets and can also be used to balance load among several servers.

Which protocol is used to communicate between a browser and a servlet ?

A browser and a servlet communicate using the HTTP protocol (a stateless request/response based protocol).

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 and the "ServletResponse", which encapsulates the communication from the servlet back to the client.In addition to both HTTP request and response, HTTP headers are informational additions that convey both essential and non-essential information.
For example: HTTP headers are used to convey MIME (Multipurpose Internet Mail Extension) type of an HTTP request and also to set and retrieve cookies etc.

Content-Type: text/html
Set-Cookie:AV+USERKEY=AVSe5678f6c1tgfd;expires=Monday, 4-Jul-2006 12:00:00; path=/;domain=.lulu.com;
response.setContentType("text/html");
response.addCookie(myCookie);


How would you get the browser to request for an updated page in 10 seconds from the server?


response.setHeader("Refresh", 10);

Refresh does not stipulate continual updates. It just specifies in how many seconds the next update should take place. So, you have to continue to supply "Refresh" in all subsequent responses. The "Refresh" header is very useful because it lets the servlet display a partial list of items or an introductory image to be displayed while the complete results or real page is displayed later (say in 10 seconds). You can also specify another page to be reloaded as follows:

respose.setHeader("Refresh", "10;URL=http://localhost:8080/myCtxt/crm.do");

The above setting can be directly set in the <HEAD> section of the HTML page as shown below as opposed to setting it in the servlet. This is useful for static HTML pages.
<META HTTP-EQUIV="Refresh" CONTENT="5; URL=http://localhost:8080/myCtxt/crm.do" />

What can you do in your Servlet/JSP code to tell browser not to cache the pages ?

Another useful header is the Cache-Control as shown below:

response.setHeader("Cache-Control","no-cache"); //document should never be cached. HTTP 1.1
response.setHeader("Pragma", "no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0);


What is the difference between request parameters and request attributes ?

Request parameters

  • Parameters are form data that are sent in the request from the HTML page. These parameters are generally form fields in an HTML form like:
    <input type="text" name="param1"/> <input type="text" name="param2"/> Form data can be attached to the end of the URL as shown below for GET requests http://MyServer:8080/MyServlet?param1=Peter¶m2=Smith or sent to the sever in the request body for POST requests. Sensitive form data should be sent as a POST request.
  • You can get them but cannot set them.
    request.getParameter("param1");
    request.getParameterNames();

Request attributes

  • Once a servlet gets a request, it can add additional attributes, then forward the request off to other servlets or JSPs for processing. Servlets and JSPs can communicate with each other by setting and getting attributes.
    request.setAttribute("calc-value", new Float(7.0));
    request.getAttribute("calc-value");
  • You can both set the attribute and get the attribute. You can also get and set the attributes in session and application scopes.

What are the different scopes or places where a servlet can save data for its processing?

Data saved in a request-scope goes out of scope once a response has been sent back to the client (i.e. when the request is completed).

//save and get request-scoped value
request.setAttribute("calc-value", new Float(7.0));
request.getAttribute("calc-value");


Data saved in a session-scope is available across multiple requests. Data saved in the session is destroyed when the session is destroyed (not when a request completes but spans several requests).

//save and get session-scoped value
HttpSession session = request.getSession(false);
If(session != null) {
session.setAttribute("id", "DX12345");
value = session.getAttribute("id");
}


Data saved in a ServletContext scope is shared by all servlets and JSPs in the context. The data stored in the servlet context is destroyed when the servlet context is destroyed.

//save and get an application-scoped value
getServletContext().setAttribute("application-value", "shopping-app");
value = getServletContext().getAttribute("application-value");


Which code line should be set in a response object before using the PrintWriter or the OutputStream ?

You need to set the content type using the setContentType("") method.

//to return an html
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(""."");
//to return an image
response.setContentType("image/gif");


HTTP is a stateless protocol, so, how do you maintain state ? How do you store user data between requests ?

This is a commonly asked interview question. 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. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. 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 basis
session.setMaxInactiveInterval(300);//resets inactivity period for this session as 5 minutes


Session tracking uses cookies by default. What would you do if the cookies are turned off ?

If cookies are turned off, you can still enable session tracking using URL rewriting. This involves including the session ID within the link as the name/value pair as shown below.
http://localhost:8080/mySite/purchase.do;jsessionid=4FB61319542B5D310B243E4BDD6DC64B
Adding session ID to each and every link is cumbersome and hence is simplified by the following methods:

response.encodeURL(givenURL) to associate a session ID with a given URL and if you are using redirection then
response.encodeRedirectURL(givenURL).
//set a value in the session
public class CRMServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
req.getSession().setAttribute("key", "ItemNo-1245");
String url = resp.encodeURL("/myWebCtxt/purchase.do");
PrintWriter pw = resp.getWriter();
pw.println("<html>Sample encoded URL --><a href='" + url + "'>purchase</a></html>");
}
}
//retrieve the previously set value from the session
public class PurchaseServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String value = (String)req.getSession().getAttribute("key");
PrintWriter pw = resp.getWriter();
pw.println("<html>Item to purchase is --> " + value +"</html>");
}
}

When you invoke the method encodeURL(givenURL) with the cookies turned on, then session ID is not appended to the URL. Now turn the cookies off and restart the browser. If you invoke the encodeURL(givenURL) with the cookies turned off, the session ID is automatically added to the URL as follows:
http://localhost:8080/myWebCtxt/purchase.do;jsessionid=4FB61319542B5D310B243E4BDD6DC64B

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 session exists, 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 session exists, it returns that session object. If a session does not already exist then it returns null.
Sessions can be timed out (configured in web.xml) or manually invalidated. Hidden Fields on the pages can maintain state and they are not visible on the browser. The server treats both hidden and non-hidden fields the same way.
<INPUT type="hidden" name="Firstname" value="Peter">
<INPUT type="hidden" name="Lastname" value="Smith">
The disadvantage of hidden fields is that they may expose sensitive or private information to others. URL re-writing will append the state information as a query string to the URL. This should not be used to maintain private or sensitive information.
Http://MyServer:8080/MyServlet?Firstname=Peter&Lastname=Smith
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. The cookie data moves in the following manner:
  • If you type the URL of a website into your browser, your browser sends the request to the Web server. When the browser does this it looks on your machine for a cookie file that URL has set. If it finds it, your browser will send all of the name-value pairs along with the URL. If it does not find a cookie file, it sends no cookie data.
  • The URLís Web server receives the cookie data and requests for a page. If name-value pairs are received, the server can use them. If no name-value pairs are received, the server can create a new ID and then sends name-value pairs to your machine in the header for the Web page it sends. Your machine stores the name value pairs on your hard disk.
Cookies can be used to determine how many visitors visit your site. It can also determine how many are new versus repeated visitors. The way it does this is by using a database. The first time a visitor arrives; the site creates a new ID in the database and sends the ID as a cookie. The next time the same user comes back, the site can increment a counter associated with that ID in the database and know how many times that visitor returns. The sites can also store user preferences so that site can look different for each visitor.

How can you set a cookie and delete a cookie from within a Servlet ?


//to add a cookie
Cookie myCookie = new Cookie("aName", "aValue");
response.addCookie(myCookie);

//to delete a cookie
myCookie.setValue("aName", null);
myCookie.setMax(0);
myCookie.setPath("/");
response.addCookie(myCookie);

Which mechanism to choose ?

HttpSession

  • There is no limit on the size of the session data kept.
  • The performance is good.
  • This is the preferred way of maintaining state. If we use the HTTP session with the application serverís persistence mechanism (server converts the session object into BLOB type and stores it in the Database) then the performance will be moderate to poor.
Note: When using HttpSession mechanism you need to take care of the following points:
  • Remove session explicitly when you no longer require it.
  • Set the session timeout value.
  • Your application server may serialize session objects after crossing a certain memory limit. This is expensive and affects performance. So decide carefully what you want to store in a session.

Hidden fields

  • There is no limit on size of the session data.
  • May expose sensitive or private information to others (So not good for sensitive information).
  • The performance is moderate.

URL rewriting

  • There is a limit on the size of the session data.
  • Should not be used for sensitive or private information.
  • The performance is moderate.

Cookies

  • There is a limit for cookie size.
  • The browser may turn off cookies.
  • The performance is moderate.
The benefit of the cookies is that state information can be stored regardless of which server the client talks to and even if all servers go down. Also, if required, state information can be retained across sessions.

Explain the life cycle methods of a servlet ?

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 by spawning a new thread for each request from the Web containerís thread pool, Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.

What would be an effective use of the Servlet init() method ?

One effective use of the Servlet init() method is the creation and caching of thread-safe resource acquisition mechanisms such, as JDBC DataSources, EJB Homes, and Web Services SOAP Mapping Registry.

How would you call a method in the EJB from a servlet ?


...
MyBeanHome home = null;
...
public void init (ServletConfig config) throws ServletException {
//1. JNDI lookup is hard coded for illustration purpose but should use a declarative
//approach involving web.xml file and server specific deployment descriptor files because
//if the server location changes, hardcoding may require reasonable amount of changes &
//testing. Lookup for JBoss server is shown below:
Properties jndiProps = new Properties();
jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
jndiProps.setProperty(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
jndiProps.setProperty(Context.PROVIDER_URL, "jnp://localhost:1099");
Context ctx = new InitialContext(jndiProps);
//2. lookup home(or localHome) interface. Shown for illustration. Should prefer using the
//Service Locator pattern. Refer Q87 in Enterprise section.
Object ref = ctx.lookup("ejb/MyBean");
home = (MyBeanHome)PortableRemoteObject.narrow(ref, MyBeanHome.class);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,
IOException
{
...
//3. create a remote or a local interface
MyBean bean = home.create();
//4. Now you can call business method on remote interface
bean.invokeBusinessMethod("");
}

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 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.

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.

Explain the directory structure of a Web application ?

The directory structure of a Web application consists of two parts:
  • A public resource directory (document root): The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.
  • A private directory called WEB-INF: which contains following files and directories:
  • web.xml: Web application deployment descriptor.
  • application server specific deployment descriptor e.g. jboss-web.xml etc.
  • *.tld: Tag library descriptor files.
  • classes: A directory that contains server side classes like servlets, utility classes, JavaBeans etc.
  • lib: A directory where JAR (archive files of tag libraries, utility libraries used by the server side classes) files are stored. Note: JSP resources usually reside directly or under subdirectories of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files from direct access. Refer Q35 in Enterprise section.

    What are the ServletContext and ServletConfig objects? What are Servlet environment objects ?

    The Servlet Engine uses both interfaces. 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.

    public class CRMServlet extends HttpServlet {
      //initializes the servlet
      public void init(ServletConfig config)throws ServletException {
        super.init(config);
      }
    ...
    }

    ServletConfig

    The ServletConfig parameters are for a particular Servlet. 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.

    Example:



    String strCfgPath = getServletConfig().getInitParameter("config");
    String strServletName = getServletConfig().getServletName();
    String strClassName = getServletContext().getAttribute("GlobalClassName");


    Servlet Interview Questions - Part 2 >>>




    Home Clouds