Tuesday, April 27, 2010

Difference between ServletConfig and ServletContext

* Signature: public interface ServletConfig
ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.

Example code:
<-servlet>
<-servlet-name>ServletConfigTest<-/servlet-name>
<-servlet-class>com.javapapers.ServletConfigTest<-/servlet-class>
<-init-param>
<-param-name>topic<-/param-name>
<-param-value>Difference between ServletConfig and ServletContext<-/param-value>
<-/init-param>
<-/servlet>

* Signature: public interface ServletContext
ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.

The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in tags in web.xml file.

Example code:
<-context-param>
<-param-name>globalVariable<-/param-name>
<-param-value>javapapers.com<-/param-value>
<-/context-param>

Difference between HttpServlet and GenericServlet

javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable

* GenericServlet defines a generic, protocol-independent servlet.
* GenericServlet gives a blueprint and makes writing servlet easier.
* GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface.
* GenericServlet implements the log method, declared in the ServletContext interface.
* To write a generic servlet, it is sufficient to override the abstract service method.

javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable

* HttpServlet defines a HTTP protocol specific servlet.
* HttpServlet gives a blueprint for Http servlet and makes writing them easier.
* HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

What is servlet mapping?

What is servlet mapping?


Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.
How is servlet mapping defined?

Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:

<-servlet-mapping>
<-servlet-name>milk<-/servlet-name>
<-url-pattern>/drink/*<-/url-pattern>
<-/servlet-mapping>

servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.
Syntax for servlet mapping as per servlet specification SRV.11.2:

A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.

1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

What is implicit mapping?

A servlet container can have a internal JSP container. In such case, *.jsp extension is mapped to the internal container. This mapping is called implicit mapping. This implicit mapping allows ondemand execution of JSP pages. Servlt mapping defined in web application has high precedence over the implicit mapping.
Example code for java servlet mapping:

<-servlet>
<-servlet-name>milk<-/servlet-name>
<-servlet-class>com.javapapers.Milk<-/servlet-class>
<-/servlet>
<-servlet>
<-servlet-name>points<-/servlet-name>
<-servlet-class>com.javapapers.Points<-/servlet-class>
<-/servlet>
<-servlet>
<-servlet-name>controller<-/servlet-name>
<-servlet-class>com.javapapers.ControllerServlet<-/servlet-class>
<-/servlet>

<-servlet-mapping>
<-servlet-name>milk<-/servlet-name>
<-url-pattern>/drink/*<-/url-pattern>
<-/servlet-mapping>
<-servlet-mapping>
<-servlet-name>points<-/servlet-name>
<-url-pattern>/pointlist<-/url-pattern>
<-/servlet-mapping>
<-servlet-mapping>
<-servlet-name>controller<-/servlet-name>
<-url-pattern>*.do<-/url-pattern>
<-/servlet-mapping>

Monday, April 26, 2010

How to avoid IllegalStateException in java servlet?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

Example servlet source code snippet:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if("success".equals(processLogin())) {
response.sendRedirect("menu.jsp");
return; // <-- this return statement ensures that no content is adedd to the response further
}
Note: This same scenario of IllegalStateException is applicable in JSP also.

What happens if you call destroy() from init() in java servlet?

destroy() gets executed and the initialization process continues. It is a trick question in servlets interview.

In java servlet, destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy() method is not supposed to and will not destroy a java servlet. Don’t get confused by the name. It should have been better, if it was named onDestroy().

The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy() gets executed and then the servlet initialization gets completed.

Servlet JSP Communication

getServletConfig().getServletContext().getRequestDispatcher(“jspfilepathtoforward”).forward(request, response);

The above line is essence of the answer for “How does a servlet communicate with a JSP page?”

When a servlet jsp communication is happening, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or on object itself.

Following is a servlet and JSP source code example to perform Servlet JSP communication. Wherein an object will be communicated to a JSP from a Servlet.

Following are the steps in Servlet JSP Communication:

1. Servlet instantiates a bean and initializes it.
2. The bean is then placed into the request
3. The call is then forwarded to the JSP page, using request dispatcher.

Example Servlet Source Code: (ServletToJSP.java)

public class ServletToJSP extends HttpServlet {
02. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
03.
04. //communicating a simple String message.
05. String message = "Example source code of Servlet to JSP communication.";
06. request.setAttribute("message", message);
07.
08. //communicating a Vector object
09. Vector vecObj = new Vector();
10. vecObj.add("Servlet to JSP communicating an object");
11. request.setAttribute("vecBean",vecObj);
12.
13. //Servlet JSP communication
14. RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/javaPapers.jsp");
15. reqDispatcher.forward(request,response);
16. }
17.}

Example JSP Source Code: (javaPapers.jsp)

<-html>
02.<-body>
03.<%
04. String message = (String) request.getAttribute("message");
05. out.println("Servlet communicated message to JSP: "+ message);
06.
07. Vector vecObj = (Vector) request.getAttribute("vecBean");
08. out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
09.%>
10.<-/body>
11.<-/html>

Explain the methods used for session tracking.

What is a session?

A session is a conversion between the server and a client. A conversion consists series of continuous request and response.
Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.

When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.

Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.
Session tracking methods:

1. User authorization
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API

The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields


Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie alogwith it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:

Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);

Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.

Session Life Cycle

How to access HttpSession object?

Every request is associated with an HttpSession object. It can be retrieved using getSession(boolean create) available in HttpServletRequest. It returns the current HttpSession associated with this request or, if there is no current session and create is true, and then returns a new session. A session can be uniquely identified using a unique identifier assigned to this session, which is called session id. getId() gives you the session id as String.

isNew() will be handy in quite a lot of situations. It returns true if the client does not know about the session or if the client chooses not to join the session. getCreationTime() returns the time when this session was created. getLastAccessedTime() returns the last time the client sent a request associated with this session.

How to store data in session?

Once you have got access to a session object, it can be used as a HashTable to store and retrieve values. It can be used to transport data between requests for the same user and session. setAttribute(String name, Object value) adds an object to the session, using the name specified. Primitive data types cannot be bound to the session.

An important note to you, session is not a bullock cart. It should be used sparingly for light weight objects. If you are in a situation where you have to store heavy weight objects in session, then you are in for a toss. Now it’s time to consult a software doctor. Your software design is having a big hole in it. HttpSession should be used for session management and not as a database.

Follow a proper naming convention to store data in session. Because it will overwrite the existing object if the name is same. One more thing to note is your object needs to implement Serializable interface if you are going to store it in session and carry it over across different web servers.
How to retrieve data from session?

getAttribute(String name) returns the object bound with the specified name in this session. Be careful while using this, most programmers fell into a deeply dug pit NullPointerException. Because it returns null if no object is bound under the name. Always ensure to handle null. Then, removeAttribute(String name) removes the object bound with the specified name from the session. Note a point; be cautious not to expose the session id to the user explicitly. It can be used to breach into another client’s session unethically.

How to invalidate a session object?

By default every web server will have a configuration set for expiry of session objects. Generally it will be some X seconds of inactivity. That is when the user has not sent any request to the server for the past X seconds then the session will expire. What do I mean by expire here. Will the browser blowup into colorful pieces? When a session expires, the HttpSession object and all the data it contains will be removed from the system. When the user sends a request after the session has expired, server will treat it as a new user and create a new session.

Apart from that automatic expiry, it can also be invalidated by the user explicitly. HttpSession provides a method invalidate() this unbinds the object that is bound to it. Mostly this is used at logout. Or the application can have an absurd logic like after the user logins he can use the application for only 30 minutes. Then he will be forced out. In such scenario you can use getCreationTime().

Generally session object is not immortal because of the default configuration by the web server. Mostly these features are left to the imagination of web server implementers. If you take Apache Tomcat 5.5, there is an attribute maxInactiveInterval. A negative value for this will result in sessions never timing out and will be handy in many situations.

import java.io.IOException;
02.import java.io.PrintWriter;
03.import java.util.Date;
04.import java.util.Enumeration;
05.
06.import javax.servlet.ServletException;
07.import javax.servlet.http.HttpServlet;
08.import javax.servlet.http.HttpServletRequest;
09.import javax.servlet.http.HttpServletResponse;
10.import javax.servlet.http.HttpSession;
11.
12.public class SessionExample extends HttpServlet {
13.
14.public void doGet(HttpServletRequest request, HttpServletResponse response)
15.throws ServletException, IOException {
16.response.setContentType("text/html");
17.PrintWriter out = response.getWriter();
18.
19.// getting current HttpSession associated with this request or, if there
20.// is no current session and create is true, returns a new session.
21.HttpSession session = request.getSession(true);
22.
23.// Calculating Hit Count
24.Integer count = (Integer) session
25..getAttribute("SessionExample.HitCount");
26.if (count == null)
27.count = new Integer(1);
28.else
29.count = new Integer(count.intValue() + 1);
30.session.setAttribute("SessionExample.HitCount", count);
31.
32.out.println("<-HTML><-HEAD><-TITLE>SessionExample<-/TITLE><-/HEAD>");
33.out.println("<-BODY>Example session servlet to "
34.+ "demostrate session tracking and life cycle");
35.
36.// Displaying the hit count
37.out.println("Hit count for your current session is " + count);
38.
39.out.println("Some basic session information:");
40.out.println("Session ID: " + session.getId() + "<-/BR>");
41.out.println("Is it a new session: " + session.isNew() + "<-/BR>");
42.out.println("Session Creation time: " + session.getCreationTime());
43.out.println("(" + new Date(session.getCreationTime()) + ")<-/BR>");
44.out.println("Last accessed time: " + session.getLastAccessedTime());
45.out.println("(" + new Date(session.getLastAccessedTime()) + ")<-/BR>");
46.out.println("Max in active time interval: "
47.+ session.getMaxInactiveInterval() + "<-/BR>");
48.// Checks whether the requested session ID came in as a cookie
49.out.println("Session ID came in as a cookie: "
50.+ request.isRequestedSessionIdFromCookie() + "<-/BR>");
51.
52.out.println("<-H2>Iteratively printing all the values "
53.+ "associated with the session:<-/H2>");
54.Enumeration names = session.getAttributeNames();
55.while (names.hasMoreElements()) {
56.String name = (String) names.nextElement();
57.String value = session.getAttribute(name).toString();
58.out.println(name + " = " + value + "<-/BR>");
59.}
60.
61.out.println("<-/BODY><-/HTML>");
62.}
63.}

URI And URL Difference

URI

A URI identifies a resource either by location or name. More often than not, most of us use URIs that defines a location to a resource. However, a URI does not have to specify the location of a specific representation. Citing and example of a W3C URI for their home image, they use the following URI: http://www.w3.org/Icons/w3c_home.

Note the absence of a file extension. The URI for the w3c_home image is still universally unique, but it does not specify the specific representation of the image (either a GIF, PNG, or JPG). The selection of the representation can be determined by the web server through HTTP content negotiation. The Apache HTTPD server has had excellent support for content negotiation for many years. Oddly, few sites take advantage of HTTP content negotiation. The W3C is one web application that makes heavy use of URIs and content negotiation.

URL

A URL is a URI but a URI is not a URL. A URL is a specialization of URI that defines the network location of a specific representation for a given resource. Taking the same W3C example, there are actually 2 representations available for the w3c_home resource:

* http://www.w3.org/Icons/w3c_home.gif
* http://www.w3.org/Icons/w3c_home.png

These URIs also define the file extension that indicates what content type is available at the URL. Through content negotiation, the web server will forward the user agent to the proper type, depending on the client’s capabilities, when the URI http://www.w3.org/Icons/w3c_home is accessed.