O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Simplifying Your JSP with a JavaBean

Problem

You want to reduce the amount of Java coding in your JSP using a JavaBean component.

Solution

Use <jsp:useBean> with the name of your bean.

Discussion

JavaBeans is Java’s component technology, analogous to COM components on MS-Windows. Recipes Section 23.8 and Section 23.9 contain a formula for packaging certain Java classes as JavaBeans. While JavaBeans were originally introduced as client-side, GUI-builder-friendly components, there is nothing in the JavaBeans specification that limits their use to the client-side or GUI. In fact, it’s fairly common to use JavaBean components with a JSP. It’s also easy and useful, so let’s see how to do it.

At the bare minimum, a JavaBean is an object that has a public no-argument constructor and follows the set/get paradigm. This means that there is regularity in the get and set methods. Consider a class, each instance of which represents one user account on a login-based web site. For the name, for example, the methods:

public void setName(String name);
public String getName(  );

allow other classes full control over the “name” field in the class but with some degree of encapsulation; that is, the program doesn’t have to know the actual name of the field (which might be name, or myName, or anything else suitable). Other programs can even get a list of your get/set methods using introspection (see Section 25.3). Example 18-14 is the full class file; as you can see, it is mostly concerned with these set and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required