File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes Initializing a useBean with some non-default value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "Initializing a useBean with some non-default value" Watch "Initializing a useBean with some non-default value" New topic

Initializing a useBean with some non-default value

eran gi

Joined: Aug 14, 2011
Posts: 3
I'm new to JSP. In a toy project of mine, I'd like to use useBeans to present data of, say, a user. Given the user has an ID, I'd like the bean to be initialized with the given ID, and have the rest of the properties loaded from the DB. In regular Java code, I'd have a User class with a constructor that gets the ID, and loads the rest of the stuff. However, beans can't do that. I was able to come up with two ways to do such initialization:

1. Have a special setter, say "setInitialize", and then set the "initialize" attribute. This is, IMO, kind of abusive, as "initialize" isn't really an attribute of the bean...
2. Use a scriptlet to explicitly call a "loadUser" method of the bean before getters are called. Possible, but dirties the page with Java code.

Most code examples I could find first set all fields using a form, and then use that data. Is it really that uncommon to initialize the bean somehow, and then just use the getters in EL? How should I better do such initialization?
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63866

All that sort of work should be done in the page controller before control gets sent to the JSP. Please read this article for more details.

[Asking smart questions] [About Bear] [Books by Bear]
I agree. Here's the link:
subject: Initializing a useBean with some non-default value
jQuery in Action, 3rd edition