Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing JavaBeans in Servlets

 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to create JavaBeans which can be accessible by servlets in my web application. 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.

-James
 
Gert Cuppens
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question "how long will a bean live" is one of my favourites.
Unfortunately, I' still looking for the answer : "which scope is the best for which application".
In your example you put "scope = 'application' ", so this is a bean that will be alive as long as the application is running.
I have seen examples of web applications where the bean has a scope of 'request'. So, as soon as the request has got a response, ie as soon as the user has his new HTML-page (or the same with new info on it), this bean is gone.
Now I'm making a web application, where I'm using a session (with the request.getSession() command) and I'm putting the Java bean in this session. In the JSP, I can get the values contained in this Java bean by using the jsp-tag
<jsp:useBean id="persoon" class="org.brukkerlin.persoon.NatuurlijkePersoon" scope="session"/>
Nevertheless I'm still hoping for a correct answer which scope you should give to a Java Bean in which circumstance.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64827
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James, yes that's pretty much the picture. Be aware that anything put into application scope needs to be accessed in a thread-safe manner.
Gert, what's your confusion? You seem to have grasped the essentials.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic