Initializing a useBean with some non-default value
posted 4 years ago
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?