<jsp:useBean> can have a body!

If you put your setter code (<jsp:setProperty>) inside the body of <jsp:useBean>, the property setting is conditional! In other words, the property values will be set only if a new bean is created. If an existing bean with that scope and id are found, the body of the tag will never run, so the property won’t be reset from your JSP code.

Note

With a <jsp:useBean > body, you can have code that runs conditionally... ONLY if the bean attribute can’t be found and a new bean is created.

image with no caption

Q:

Q: Why didn’t they just let you specify arguments to the constructor of the bean? Why do you have to go through the extra trouble of setting values anyway?

A:

A: The simple answer is this: beans can’t HAVE constructors with arguments! Well, as a Java class, they can, but when an object is going to be treated as a bean, Bean Law states that ONLY the bean’s public, no-arg constructor will be called. End of story. In fact if you do NOT have a public no-arg constructor in your bean class, this whole thing will fail anyway.

Q:

Q: What the heck is Bean Law?

A:

A: The law according to the creakingly-ancient JavaBeans specification. We’re talking JavaBeans—NOT Enterprise JavaBeans (EJB) which is completely unrelated. (Go figure.)The plain old non-enterprise JavaBeans spec defines what it takes for a class to be a JavaBean. Although the spec actually gets pretty complex, the only things you need to know for using beans with JSP and servlets are these few rules (we’re showing only those that apply to what we’re doing with servlets and JSPs):

1) You MUST have a public, no-arg constructor.

2) You MUST name your public getter and setter methods starting with “get” (or “is”, for a boolean) and “set”, followed by the same word. (getFoo(), setFoo()). The property name is derived from stripping off the “get” and “set”, and changing the first character of what’s left to lowercase.

3) The setter argument type and the getter return type MUST be identical. This defines the property type.

int getFoo()    void setFoo(int foo)

4) The property name and type are derived from the getters and setters and NOT from a member in the class. For example, just because you have a private int foo variable does NOT mean a thing in terms of properties. You can name your variables whatever you like. The “foo” property name comes from the methods. In other words, you have a property simply because you have a getter and setter. How you implement them is up to you.

5) For use with JSPs, the property type SHOULD be a type that is either a String or a primitive. If it isn’t, it can still be a legal bean, but you won’t be able to rely only on standard actions, and you might have to use scripting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset