Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Create Application Object  RSS feed

 
Steve Wood
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

This is likely going to strike some people as a stupid question, but here goes:

What is the best way to instantiate an application scope object in JSP - and make sure it's only instantiated if it doesn't already exist?

Any help is greatly appreciated.

All the best,

Steve
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66186
146
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming that the object is bean-patterned, use the <jsp:useBean> action with a scope attribute of "application".
 
Steve Wood
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear,

Yup, I believe it's bean patterned. Does the server automatically manage the application object for you? i.e. you don't need to check it actually exists.

I guess I'm not sure how you actually create the object.

I kind of see it like:

if (applicationScopeObject == null)
{
applicationScopeObject = new MyObject();
}

...

I'll have a look at the documentation again. I just don't seem to get it.

All the best,

Steve
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66186
146
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The <jsp:useBean> action will check to see if an obkect with the specified name already exists. If it does not, it will create one. Hence, the need for the zero-arg constructor.

Read the docs on useBean for more info. Or better yet, take a look at the .java file that your container creates on the behalf of your JSP page to see what code the <jsp:useBean> action gets translated into.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66186
146
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here, in fact, is an example from one of my JSPs. It uses page scope, but that's moot.

In the JSP:



the resulting translation (by Tomcat 5.0.25):



Note how the code fetches the scoped variable, and then, if the result of that fetch is null, it creates a new instance of the bean using a zero-arg constructor and sets it back into the scope (as well as into a scripting variable).
 
Steve Wood
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear,

That makes a lot of sense - big help.

All the best,

Steve
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!