JavaBeans in JSP: Design, Use, and Sharing, Slides of Java Programming

An overview of javabeans, their design conventions, and their use in jsp pages. It covers the benefits of using javabeans, such as easier content generation, stronger separation between content and presentation, higher reusability of code, and simpler object sharing. The document also explains how to instantiate, access, and set properties of javabeans using jsp elements like jsp:usebean, jsp:getproperty, and jsp:setproperty.

Typology: Slides

2011/2012

Uploaded on 08/09/2012

dhanyaa
dhanyaa 🇮🇳

4.7

(3)

60 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Slide1
Slide2
Agenda
fall 2009cs420
JavaBeans for JSP
Reference
www.javapassion.com/j2ee
coreservlets.com

docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download JavaBeans in JSP: Design, Use, and Sharing and more Slides Java Programming in PDF only on Docsity!

Slide 2

Agenda

cs420 fall 2009

Ž JavaBeans for JSP

Ž Reference

  • www.javapassion.com/j2ee
  • coreservlets.com

What are JavaBeans?

cs420 fall 2009

ŽJava classes that can be easily reused and composed together into an application ŽAny Java class that follows certain design conventions can be a JavaBeans component

  • properties of the class
  • public methods to get and set properties ŽWithin a JSP page, you can create and initialize beans and get and set the values of their properties ŽJavaBeans can contain business logic or data base access logic

JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component. JavaBeans component design conventions govern the properties of the class and govern the public methods that give access to the properties. JavaServer Pages technology directly supports using JavaBeans components with JSP language elements. You can easily create and initialize beans and get and set the values of their properties And JavaBeans can contain business logic or database access logic.

Slide 4

JavaBeans Design Conventions

cs420 fall 2009

ŽJavaBeans maintain internal properties ŽA property can be

  • Read/write, read-only, or write-only
  • Simple or indexed

A JavaBeans component property can be

  • Read/write, read‐only, or write‐only
  • Simple, which means it contains a single value, or indexed, which means it represents an array of values There is no requirement that a property be implemented by an instance variable; the property must simply be accessible using public methods that conform to certain conventions:
  • For each readable property, the bean must have a method of the form PropertyClass getProperty() { ... }
  • For each writable property, the bean must have a method of the form setProperty(PropertyClass pc) { ... } In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters. If there are no other constructors, no arg constructor is automatically generated.

Why to use accessor methods?

cs420 fall 2009

Ž You can put constraints on values

public void setSpeed(double newSpeed) { if (newSpeed < 0) { sendErrorMessage(...); newSpeed = Math.abs(newSpeed); } speed = newSpeed; }

Ž If users of your class accessed the fields directly, then they would each be responsible for checking constraints.

Slide 8

Why to use accessor methods?

cs420 fall 2009

Ž You can change your internal representation

without changing interface

// Now using metric units (kph, not mph) public void setSpeed(double newSpeed) { setSpeedInKPH = convert(newSpeed); } public void setSpeedInKPH(double newSpeed) { speedInKPH = newSpeed; }

Why to use accessor methods?

cs420 fall 2009

Ž You can perform arbitrary side effects

public double setSpeed(double newSpeed) {

speed = newSpeed;

updateSpeedometerDisplay();

ŽIf users of your class accessed the fields directly,

then they would each be responsible for

executing side effects.

ŽToo much work and runs huge risk of having

display inconsistent from actual values.

Slide 10

Example: JavaBeans

cs420 fall 2009

public class Currency { private Locale locale; private double amount; public Currency() { locale = null; amount = 0.0; } public void setLocale(Locale l) { locale = l; } public void setAmount(double a) { amount = a; } public String getFormat() { NumberFormat nf = NumberFormat.getCurrencyInstance(locale); return nf.format(amount); } }

In the BookStore application, the JSP pages catalog.jsp, showcart.jsp, and cashier.jsp use the util.Currency JavaBeans component to format currency in a locale‐sensitive manner. The bean has two writable properties, locale and amount, and one readable property, format.

The format property does not correspond to any instance variable, but returns a function of the locale and amount properties.

Compare the Two

cs420 fall 2009

<% ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); // If the user has no cart object as an attribute in Session scope // object, then create a new one. Otherwise, use the existing // instance. if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } %> versus <jsp:useBean id="cart" class="cart.ShoppingCart“ scope="session"/>

Now compare the two JSP codes. As you can tell JavaBeans based JSP code is a lot more simpler and easy to understand and would be easier to maintain. In other words, for web page authors, using JavaBeans syntax is a lot easier than writing Java code.

Why Use JavaBeans in JSP Page?

cs420 fall 2009

ŽNo need to learn Java programming language

for page designers

ŽStronger separation between content and

presentation

ŽHigher re usability of code

ŽSimpler object sharing through built-in sharing

mechanism

ŽConvenient matching between request

parameters and object properties

So just to summarize why you want to use JavaBeans over pure Java code, there are several reasons. First, page authors do not have to know Java programming language in order to use JavaBeans in JSP page because usage syntax of JavaBeans is very simple. Because content generation or business logic is captured in the form of JavaBeans component, it provides a stronger separation between content and presentation. And a single JavaBean can be in fact reusable in other JSP pages. JavaBeans also make it easier to share objects among multiple JSP pages or between requests. Finally JavaBeans greatly simplify the process of reading request parameters, converting from strings, and stuffing the resuts inside objects.

Slide 15

Using Beans - Basics

cs420 fall 2009

Ž jsp:useBean

  • In the simplest case, this element builds a new bean. It is normally used as follows:
  • <jsp:useBean id=" beanName " class=" package****. Class " /> Ž jsp:getProperty
  • This element reads and outputs the value of a bean property. It is used as follows:
  • <jsp:getProperty name=" beanName “ property=" propertyName " /> Ž jsp:setProperty
  • This element modifies a bean property (i.e., calls a method of the form set Xxx ). It is normally used as follows:
  • <jsp:setProperty name=“ beanName” property=“ propertyName “ value=" propertyValue " />

Setting Properties - jsp:setProperty

cs420 fall 2009

Ž Format

  • <jsp:setProperty name=" name “ property=" property value=" value " />

Ž Purpose

  • Allow setting of bean properties (i.e., calls to set Xxx methods) without explicit Java programming

Ž Notes

  • <jsp:setProperty name="book1“ property="title“ value="Core Servlets and JavaServer Pages" /> is equivalent to the following scriptlet <% book1.setTitle("Core Servlets and JavaServer Pages"); %>

Slide 19

Deployment

cs420 fall 2009

Ž Beans installed in normal Java directory

  • /WEB-INF/classes/ directoryMatchingPackageName Ž Beans (and utility classes) must always be in packages!

Example Bean

cs420 fall 2009

Slide 21

Example JSP page

cs420 fall 2009

<jsp:useBean id="stringBean“ class="coreservlets.StringBean" />

  1. Initial value (from jsp:getProperty): ****
  2. Initial value (from JSP expression): **<%= stringBean.getMessage() %>**
  3. **** Value after setting property with jsp:setProperty: ****
  4. **<% stringBean.setMessage ("My favorite: Kentucky Wonder"); %>** Value after setting property with scriptlet: **<%= stringBean.getMessage() %>**

Example: jsp:setProperty with Request

parameter

cs420 fall 2009

<jsp:setProperty name="bookDB"property="bookId"/> is same as <% //Get the identifier of the book to display String bookId = request.getParameter("bookId"); bookDB.setBookId(bookId); ... %>

The Duke's Bookstore application demonstrates how to use the setProperty element and a scriptlet to set the current book for the database helper bean. For example, bookstore3/web/bookdetails.jsp uses the form: <jsp:setProperty name="bookDB" property="bookId"/> whereas bookstore2/web/bookdetails.jsp uses the form: <% bookDB.setBookId(bookId); %>

Slide 25

Example: jsp:setProperty with Expression

cs420 fall 2009

<jsp:useBean id="currency" class="util.Currency" scope="session"> <jsp:setProperty name="currency" property="locale“ value="<%= request.getLocale() %>"/> </jsp:useBean>

<jsp:setProperty name="currency" property="amount" value="<%=cart.getTotal()%>"/>

The above fragments from the page bookstore3/web/showcart.jsp(of Java WSDP) illustrate how to initialize a currency bean with a Locale object and amount determined by evaluating request‐time expressions. Because the first initialization is nested in a useBean element, it is only executed when the bean is created.

Getting JavaBeans Properties

without Converting it to String

cs420 fall 2009

ŽMust use a scriptlet

ŽFormat

<% Object o = beanName.getPropName(); %>

ŽExample

<% // Print a summary of the shopping cart int num = cart.getNumberOfItems(); if (num > 0) { %>

If you need to retrieve the value of a property without converting it and inserting it into the out object, you must use a scriptlet: <% Object o = beanName.getPropName(); %> Note the differences between the expression and the scriptlet; the expression has an = after the opening % and does not terminate with a semicolon, as does the scriptlet.

Slide 29

Sharing Beans

cs420 fall 2009

Ž You can use the scope attribute to specify additional places where bean is stored

  • Still also bound to local variable in _jspService
  • <jsp:useBean id="…" class="…” scope="…" /> Š Lets multiple servlets or JSP pages share data Ž Also permits conditional bean creation
  • Creates new object only if it can't find existing one

Scope Attribute

cs420 fall 2009

Ž page (<jsp:useBean … scope="page"/> or <jsp:useBean…>)

  • Default value. Bean object should be placed in the PageContext object for the duration of the current request. Lets methods in same servlet access bean Ž Application (<jsp:useBean … scope="application"/>)
  • Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()).
  • ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined).

Slide 31

Scope Attribute

cs420 fall 2009

Ž session (<jsp:useBean … scope="session"/>)

  • Bean will be stored in the HttpSession object associated with the current request, where it can be accessed from regular servlet code with getAttribute and setAttribute, as with normal session objects. Ž request (<jsp:useBean … scope="request"/>)
  • Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute

Summary

cs420 fall 2009

Ž Benefits of jsp:useBean

  • Hides the Java syntax
  • Makes it easier to associate request parameters with Java objects (bean properties)
  • Simplifies sharing objects among multiple requests or servlets/JSPs Ž jsp:useBean
  • Creates or accesses a bean Ž jsp:getProperty
  • Puts bean property (i.e. get Xxx call) into servlet output Ž jsp:setProperty
  • Sets bean property (i.e. passes value to set Xxx )

Slide 35

Summary &

Questions?

fall 2009 cs

That’s all for today!