Oxxus » Tutorials » JSP tutorial » Using JSP & JavaBeans

Using JSP & JavaBeans

When the JSP engine encounters a jsp:useBean action, the JSP engine searches for a bean with the same id and scope as the bean cited in the jsp:useBean action.

If such a bean is not found, the JSP engine generates code to create the bean. If such a bean is found, the JSP engine makes that bean available to the page containing the jsp:useBean action. Beans may have the same id but be instantiated from different classes.

If so, the JSP engine generates code to do a cast. If the cast is illegal, the generated servlet throws a ClassCastException. As a result of this bean usage, multiple visits to the same page containing a jsp:useBean action during the same session will not create multiple beans.

Another consequence of this use involves conditionally executing JSP commands, as explained in the following. The examples of jsp:useBean you ve seen use the empty tag XML syntax form.However, you can code the jsp:useBean construct by using separate opening and closing tags as follows:

Virtual private server hosting fully supports JSP pages. Back to the example:

<jsp:useBean id=someBeanName& > Static HTML, JSP commands, whatever </jsp:useBean>

The virtue of using separate opening and closing tags is that the code sandwiched between the tags is executed only if the bean instance does not exist.

If you want to share a bean among several pages, you can place the same code in every page, knowing that the code gets executed once, depending on where the bean gets created. Remember, JSP knows the bean by the values of the jsp:useBean attributes id and class. Different beans (objects) may be the "same" bean to JSP.

Using JavaBeans in Multiple JSPs The syntax of the jsp:useBean action has a couple of additional parameters, as follows, which have not been mentioned:

<jsp:useBean id="beanInstanceName" class="className" scope="beanScope" type="classType" />

The scope attribute is the focus of our discussion. The value of the scope attribute governs the bean s visibility. Different values for the scope attribute place instantiated beans within different contexts.Refer to Table 4-3 in Chapter 4 for a list of scope attribute values and the relevant contexts.

The default scope attribute value is page. Page scope means that bean instances are accessible on the existing JSP, or the JSP containing the jsp:useBean action. Stated differently, other JSPs within your application cannot use instantiated bean objects without containing a jsp:useBean action.

Contact sales!