OOP-ResearchMake It Simpler by Object Oriented Programming

Tips for JSP/Servlet programming by Java API from OOP-Research

By Java API from OOP-Research, the development of web applications or WAP services will be easier. A few lines of codes are enough for your JSP or Servlet programming to use XML, JDBC or JavaMail API. Your JSP/Servlet can accept HTTP POST requests with multipart/form-data encode for file upload. And HTTP POST request parameters with Japanese Shift_JIS, Chinese BIG5, Chinese GB2312 or Russian KOI8-R can be decoded easily. Or, the unique session ID can be generated per each user login and a series of HTTP requests can be tracked by this session ID even without Cookie.

Most of these Java APIs are Thread Safe and only a single instance is enough within each web application context. Due to these characteristics, our Java APIs have very similar interfaces. Once you are familiar with any of them, you can easily use the rest of them. It is another benefit of Java API from OOP-Research. This article describes the Tips for JSP/Servlet programming by Java API from OOP-Research. The source code of a example Servlet is also listed here.

We strongly recommend you to read through this article before you start to develop your web applications or WAP services, if your use any of the Java APIs listed below:


OOP XX API is Thread Safe. What does this mean?

This means that: Most of the methods on the core class of our Java API is Thread Safe. In other words, on the single instance of that class, you can call these methods concurrently. This very simple fact will give you so much benefits.

Because JSP/Servlet on Apache Tomcat must be prepared for the multiple simultaneous requests, you must make your JSP/Servlet Thread Safe, unless your JSP/Servlet implements Single Thread Model interface. As a general rule, the scope of most of the variables should fall within:

  • doGet(HttpServletReqeust, HttpServletResponse)
  • doPost(HttpServletReqeust, HttpServletResponse)

. And only the static variables can be class-scoped. This causes so many garbage-collection of method-scoped variables for those methods. While the modern JVMs in these days are well designed for avoiding the over-heads related with garbage-collection, it is desirable to keep method-scoped variables as less as possible.

But, because most of the methods of the core class in our Java API are Thread Safe, your JSP/Servlet can keep the class-scoped reference to its instance and can call these Thread Safe methods on it within:

  • doGet(HttpServletReqeust, HttpServletResponse)
  • doPost(HttpServletReqeust, HttpServletResponse)

Moreover, only the single instance can be shared among the multiple JSP/Servlet within a web application context.

Thread Safe on a single instance

Not only that Thread Safe implementation will result in a significance performance improvement in your JSP/Servlet, it will make your JSP/Servlet simpler ones due to the similar interface of our Java API.

Only one time Initialization

To make a single instance being shared among the multiple JSP/Servlet within a web application context, every core class of our Java APIs implements the static method which always returns the same instance of that class. It is:

  • getInstance( )

This static method works in the 2 different ways, because only the first call of this method needs to initialize the instance of that class, and the subsequent calls must return the same instance as the first call. As for the first call, this method will:

  1. Read the property file from WEB-INF/classes.
  2. Based on the properties, initialize the instance of that class.
  3. If required, read the initial data from SQL tables.
  4. Return the instance which was created in the second step.

But, all the subsequent calls always return the same instance which is returned by the first call. Thus, this method gives us the way to get the reference to the single instance from anywhere within a web application context. By this method, any JSP or Servlet within the same web application context can share the single instance. Do not use the constructor to initialize the instance of the class. Instead, all you have to do is:

  • Foo bar=Foo.getInstance( );

It is easy, isn't it? By the way, you may have noticed that the first call of this method may be somewhat heavy task. Yes, it is desirable to avoid calling this method within:

  • doGet(HttpServletReqeust, HttpServletResponse)
  • doPost(HttpServletReqeust, HttpServletResponse)

. Rather, the best place to live for this method is:

  • init( )

and your JSP/Servlet can keep the class-scoped variable for the returned instance. Then,

  • doGet(HttpServletReqeust, HttpServletResponse)
  • doPost(HttpServletReqeust, HttpServletResponse)

can call other methods on it, because they are Thread Safe. Anyway, the source fragment of your Servlet will look like this:


private static MimeParser parser=null;
public void init()
    throws ServletException{
    try{
        // Get the instance of MimeParser...
        parser=MimeParser.getInstance();
    }
    catch(Exception ex){
        throw (new ServletException(ex));
    }
}

public void doPost(HttpServletRequest req,
                   HttpServletResponse res)
    throws ServletException,IOException{
    try{

        // Parse the text values submitted from TEXT INPUT
        // or SELECTION.
        // At the same time, the files uploaded from FILE
        // INPUT are saves into the local file system on
        // the server side.
        // The text will be decoded using Shift_JIS.
        // The file will be saved under "foo" directory.
        ParsedData data=parser.parse(req,"Shift_JIS","foo");

        // Now, you can retrieve the text value for TEXT
        // INPUT whose name is "user"...
        String user=data.getParameter("user");
        ...
        ...

The above Servlet gets the single instance of MimeParser, which is the core class of OOP MimeParser. The rest of the Servlets within the same web application may also implement the same init( ) method, and the same instance of MimeParser can be shared among them.
Thus, you can take the full advantage of OOP-Research's Java APIs and can make your JSP/Servlet Thread Safe easily.

Benefit of load-on-startup in web.xml

NOTE:
This article was written when Servlet 2.2 Spec was finalized. If your environment complies with Servlet 2.3 Spec, ServletContextListner will be the better place for this job. For details, please read J2EE tech Tip.

Some of our Java API requires simple clean-up tasks at the end of the life cycle of its instance. For example, PooledPS, the core class of OOP PooledStatement, implements the pooling mechanism of JDBC PreparedStatement. Before its instance (the single instance, of course) is garbage-collected, all the JDBC Connection available in its pool should be closed. So, before exiting JVM, we should call:

  • PooledPS.closeIfOpen();

, which closes all the JDBC Connections to SQL database. Another example is MailScheduler, the core class of OOP MailScheduler. Its instance keeps the background Thread running, which sends the e-mails at the scheduled time. To start/stop this background Thread, we should call:

  • MailScheduler.getInstance(smtp).startScheduler();
  • MailScheduler.getInstance().stopScheduler();

independently from the HTTP requests from the web browser. As you know, the best places for these start-up and clean-up tasks are:

  • init( )
  • destroy( )

of your Servlet. Apache Tomcat (or any other JSP/Servlet server) calls these methods on all the available Servlets in it, at the boot time and before it shutdowns correspondingly. For example, one of your Servlets may implement:


public void init()
    throws ServletException{
    try{
        PooledPS.getInstance();
        SimpleSMTP smtp=SimpleSMTP.getInstance();
        MailScheduler.getInstance(smtp).startScheduler();
    }
    catch(Exception ex){
        throw (new ServletException(ex));
    }
}

public void destroy(){
    MailScheduler.getInstance().stopScheduler();

    // Because MailScheduler depends on PooledPS,
    // call this method at the very last!
    PooledPS.closeIfOpen();
}

Because both of start-up and clean-up tasks should be done only once, only one Servlet should be responsible for these tasks. The good practice is to define a special kind of Servlet (you can think of it dummy Servlet), whose purposes are:

  • the initialization of the shared instances
  • the start-up tasks
  • the clean-up tasks

only. Such a Servlet does not need to implement any of:

  • doGet(HttpServletReqeust, HttpServletResponse)
  • doPost(HttpServletReqeust, HttpServletResponse)

Because any HTTP requests will never arrive in that Servlet, the Servlet must be loaded into Apache Tomcat (or any other JSP/Servlet server) explicitly. In the web.xml for your web application context, load-on-startup element can force Apache Tomcat (or any other Servlet server) to load the Servlet at the start-up time of the server. For example, assuming that the class name of the Servlet is InitAndDestroy, your web.xml will include the elements like below:


    <servlet>
        <servlet-name>
            dummy
        </servlet-name>
        <servlet-class>
            InitAndDestroy
        </servlet-class>
        <load-on-startup>
        1
        </load-on-startup>
   </servlet>

Then, Apache Tomcat (or any other Servlet server) will load this dummy Servlet and call its init( ) destroy( ) methods. Thus, by the benefit of load-on-startup mechanism, dummy Servlet can play a significant role in your web applications or WAP services while it is invisible to the users.

Caution!
All the APIs for Servlet/JSP introduced by this web site are now included in Bento framework:
  • Simpler than JSTL or Apache Struts
  • MVC framework by HTML
  • Input validation from CGI FORM
  • Easy user authentication
  • Easy localization (L10n)
To download the APIs and source code examples, please visit the web site of Bento framework.


JBuilder 2007


General Information

For Java Development

Java and all Java-based trademarks and logos are trademarks or registered of Sun Microsystems, Inc. in the United States and other countries.


ALL CONTENTS COPYRIGHT 1997-2007, OOP-Research Corporation. All rights reserved.