Well it is true that you have to take care for the ways classes are 
loaded (ServletEngines do have their own dynamic class loader 
normally)
but there are for sure endless scenarios how you can share
common resources.


I.
Here are some simple scenarios:

1. You want to share common methods between the servlets

Create an abstract parent class that derives from a Servlet (guess 
most likely HttpServlet) and derive your base of "working" servlets 
from that class.
i.e.

public abstract class MyMailSystemServlet extends HttpServlet {
...
...

}//class MySystemServlet

public class ReadMailServlet extends MyMailSystemServlet {

}//class ReadMailServlet

public class SendMailServlet extends MyMailSystemServlet {

}//class SendMailServlet

etc.

Important is that you dont forget to make the methods you define in 
the "base" servlet accessible to your subclassed servlets. Which 
means they should be marked protected. Also never forget that you 
have got a multithreaded environment (!).

2. You want to share user/session specific data

In that case I would suggest to work with a specific class i.e.
mySessionData. The reference to this class can simply be stored
in a Session, in combination with the idea of 1. a nice common method 
for a system would be following:


/**
  * Accessor method for session data stored in the HttpSession.<br>
  * Takes care about new incoming sessions by creating a new SessionData
  * instance and storing it in the HttpSession.
  *
  * @param req reference to HttpServletRequest instance.
  * @param res reference to HttpServletResponse instance.
  * @return SessionData reference to session specific mySessionData instance.
  */
  protected SessionData getSessionData(HttpServletRequest req,
                                      HttpServletResponse res){

        SessionData SD=null;

        //get the http session
        HttpSession websession = req.getSession(true);
        //in case of a new session
        if (websession.isNew()) {
                //create a new session data instance
                SD=new SessionData();
                //flag it is not only new but also not authenticated
                SD.setAuthenticated(false);
                //save a reference in the HttpSession
                websession.putValue("MySystem.SessionData",SD);
        }
        else {
                //in case of a existing valid session, return the stored
                //reference
                SD=(SessionData)websession.getValue("MySystem.SessionData");
        }
        return SD;
  }//getSessionData



  public class SessionData {

  //Members & Associations
  private boolean newsession;
  private boolean authenticated;
  ...
  ...
  private MailSession mailsession

        public SessionData() {
                newsession=true;
        }//Constructor

        public SessionData(boolean auth){

        }//Constructor:boolean

  /**
   * Accessor method for the newsession member.
   * Can be used to check if the SessionData instance
   * belongs to a newly created session.
   *
   * @return b boolean that represents the states new or not new.
   */
   public boolean isNewSession(){
        return newSession;
   }//isNewSession


  /**
   * Mutator method for the newsession member.
   * Can be used to flag that its a returning session.
   */
   public void SessionReturned(){
        newSession=false;
   }//returned

  /**
   * Mutator method to flag session being in authenticated
   * or anonymous state.
   *
   * @param b boolean that represents the state to be set.
   */
   public void setAuthenticated(boolean b){
        authenticated=b;
   }//setAuthenticated

  /**
   * Accessor method to see if session is authenticated
   * or anonymous.
   *
   * @return b boolean that represents the states authenticated or not
   *          authenticated.
   */
   public boolean isAuthenticated(){
        return authenticated;
   }//isAuthenticated

}//class SessionData


Now this above allows us to come up with nice and maybe also robust 
error handling.
Therefore we simply extend the SessionData with following associtation and
methods:

private WebError error;
private boolean failed;


  /**
   * Accessor method for WebError member.
   *
   * @return WebError that describes what failed in a request before.
   */
   public WebError getError(){
        failed=false;
        return error;
   }//getError

  /**
   * Mutator method for WebError member.
   *
   * @param we WebError that describes a failure that occured.
   */
   public void setError(WebError we){
        failed=true;
        error=we;
   }//setError


  /**
   * Accessor method for failed member.
   *
   * @return boolean that describes the states failed or not failed.
   */
   public boolean isFailed(){
        return failed;
   }//hasFailed


Imagine you are using the ElementConstruction Set, and you program some nice
WebError class implementing or extending a throwable, the error can simply be
communicated to the user, especially if all calls are routed through the
service(...) method.


Somwhere in your code.......
        try {
                //hairy stuff that can fail, maybe temporarily
        } catch (Exception ex) {
                //can be cleaned up ?

                //has to be communicated
                throw new WebError(..........);
        }




The service method.....

/**
  * Method overidden for error handling and dispatching...
  */
  public void service(HttpServletRequest req, HttpServletResponse res)
                                                          throws ServletException, 
IOException{


   SessionData mySD=null;
     try{
        //get the session's data
                mySD=getSessionData(req,res);
                //check about returning or new sessions
                if(mySD.isNewSession()) {
                        //flag that session is no longer new
                        mySD.SessionReturned();
                        //do maybe other stuff

                }
                else {
                        //check if session failed
                        if(mySD.isFailed()){
                                //get the weberror and make it display itself
                                mySD.getError().display();
                                return;
                        } else {
                                //do stuff .....
                        }
                }
                //...ensure parameters are parsed....
                //...dispatch incoming request .... etc.

        } catch (WebError we) {
                handleWebError(res,mySD,we);
        }
  }//service


Another common method....
/**
  * WebError handling routine...
  */
  protected void handleWebError(HttpServletResponse res, SessionData 
sd, WebError we){
        //we store and flag the error in the SessionData
        sd.setError(we);

        //and optionally redirect....
        try {
                        //code to ensure that you can redirect
                        //(e.g. Output not allready closed etc...)
                        res.sendRedirect(res.encodeRedirectUrl(errorurl));
        } catch (IOException ex) {
                        //this is severe...but well in any case
                        // the user will press reload or
                        //back I am quite sure about that...
        }
  }//handleWebError


3. the Singleton story....

For those who never heard about it...
A Singleton is a creational pattern that reflects the intent to 
ensure a class has only one instance, and provide a global point of 
access to it.

In Java this would be a class that can only be instantiated once, and that
has a static method getInstance(). Or it could be simply a class that 
has only static methods and throws an Exception if somebody tries to 
instantiate it.

However if you created a "base" servlet you derive from, you can also 
use that one to access or share common resources in a "singleton" 
manner....just add static members and (maybe also synchronized) 
protected accessors....

And the warning again:
Be especially careful accessing this resources, you are in a 
multithreaded environment.

Well this alltogether should allready have given you some simple case 
ideas. Now use your imagination, and I am sure you can come up with 
anything you can think about.


II.
Now we go for the complex cases...well one way is to build something 
like they are obviously trying with Turbine. Means that you get 
yourself a framework by either constructing it, or downloading it 
from java.apache. org maybe soon :)
,a framework that does all the nice things allready covered by jon 
before (e.g persistance solutions, object caching, pools for threads 
and jdbc connections etc. etc.)

Or you opt for a very extensible solution using kind of special 
ApplicationServer in the background, passing only objects or EJBs to 
and from servlets, via CORBA or RMI or
You see whatever you can think of :)

Somehow I have the feeling that all this drops under "Application 
Server" nowadays, but who knows, borders are not defined exactly yet.

I hope that helped a little bit
Regards
Dieter Wimberger


>In our application, we have around 3-4 servlets based upon the broad
>functionalities of the system.
>What we want to know is that how do we share common information between
>these servlets. Can we have something global across servlets. Or can we
>access variables of one servlet in some other servlet.
>What is the usual way of doing this. Any pointers to some working examples
>on servlet designing etc. will also be appreciated.
>
>TIA and Rgds,
>Kaustubh



------------------------------------------------------------
To subscribe:    [EMAIL PROTECTED]
To unsubscribe:  [EMAIL PROTECTED]
Problems?:       [EMAIL PROTECTED]

Reply via email to