Accessing JavaBeans in Servlets


Web tier: servlets, JSP, Web frameworks: Accessing JavaBeans in Servlets

  1. Accessing JavaBeans in Servlets (1 messages)

    I want to create JavaBeans which can be accessible by all servlets of my web application (application scope). One of these beans will essentially provide acess to a Vector of message texts that users (via the servlets) will add to or read. The other bean will be an JMX MBean that will be used by the servlets to record user activity.

    Is accessing these beans as simple as getting them from the ServletContext via the getAttribute() method ? I assume that this is analogous to using <jsp:useBean id="beanName" class="BeanClass" scope="application"> in a JSP. Am I mistaken ?

    How long will the beans "live", i.e. how long will they maintain their state ? I assume that they will "live" as long as the server is running, in that if a bean has a List or Vector which has 200 items added to it on the first day then it will still show those 200 items two days or two weeks later if the server is still running. Is this correct ?

    Thanks in advance for any feedback.

  2. Accessing JavaBeans in Servlets[ Go to top ]

    All of your assumptions are correctly. "Application scope" is the same as storing data in the ServletContext.

    If the data is mission-critical, though, you will probably want to save it into a database. If the data is more like an audit-log, you will probably want to save it into a file.

    If the data is static (like for populating select lists), putting it into the ServletContext is the best approach. You can initialized data in the init() method of an InitServlet, that has a <load-on-startup> value in your web.xml file.