Why Use a JavaBeans Component?

A JSP page can create and use any type of Java programming language object within a declaration or scriptlet. The following scriptlet creates the bookstore shopping cart and stores it as a session attribute:

<% 
   ShoppingCart cart = (ShoppingCart)session. 
      getAttribute("cart"); 
   // If the user has no cart, create a new one 
   if (cart == null) {
      cart = new ShoppingCart(); 
      session.setAttribute("cart", cart); 
   } 
%> 

If the shopping cart object conforms to JavaBeans conventions, JSP pages can use JSP elements to create and access the object. For example, the Duke’s Bookstore pages bookdetails.jsp, catalog.jsp, and showcart.jsp replace the scriptlet with the much more concise JSP useBean element:

 <jsp:useBean id="cart" class="cart.ShoppingCart" ...

Get J2EE™ Tutorial, The now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.