reset password

Data Initialization in Servlet

Consider the following example:

public class Foo extends HttpServlet {

    private List<String> data = new ArrayList<String>(); // (1)

    public Foo()
    {
        super();
        data = new ArrayList<String>(); // (2)
    }

    public void init(ServletConfig config) throws ServletException
    {
        super.init( config );
        data = new ArrayList<String>(); // (3)
    }

Note that data can be initialized in three difference places:

(1) Instance Variable Initializer (or Instance Initializer) [3]

The benefit of doing this is avoiding to repeat the same initialization code in multiple constructors. The drawback is that instance initializer cannot make forward references, and because instance initializer is executed before constructors, it cannot refer to variables initialized by a constructor.

(2) Constructor

The benefits and drawbacks are kind of the reverse of the ones for instance initializer.

(3) init(ServletConfig config)

This is specific to Servlet. According to [1], In JDK1.0, which Servlet originally was written for, constructors for dynamically loaded classes like Servlet cannot take arguments. If data initialization requires access to ServletConfig or ServletContext, it should be done in init().

References

1. http://www.geekinterview.com/talk/6554-constructor-and-init.html

2. http://forums.sun.com/thread.jspa?threadID=480900&messageID=2241219

3. http://www.javaworld.com/javaworld/jw-03-1998/jw-03-initialization.html?page=4

This page has been viewed 3524 times.