ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Web Server Java -- Servlets and JSP
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

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 and 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. Example 18-14 is the full class file; as you can see, it is mostly concerned with these set and get methods.


Example 18-14: User.java, a class usable as a bean

/** Represents one logged in user 
 */
public class User {
 
  protected String name;
  protected String passwd;
  protected String fullName;
  protected String email;
  protected String city;
  protected String prov;
  protected String country;
 
  protected boolean editPrivs = false;
  protected boolean adminPrivs = false;
 
  /** Construct a user with no data -- must be a no-argument
   * constructor for use in jsp:useBean.
   */
  public User(  ) {
  }
 
  /** Construct a user with just the name */
  public User(String n) {
    name = n;
  }
 
  /** Return the nickname. */
  public String getName(  ) {

  }
 
  public void setName(String nick) {
    name = nick;
  }
 
  // The password is not public - no getPassword.
 
  /** Validate a given password against the user's. */
  public boolean checkPassword(String userInput) {
    return passwd.equals(userInput);
  }
 
  /** Set password */
  public void setPassword(String passwd) {
    this.passwd = passwd;
  }
 
  /** Get email */
  public String getEmail(  ) {
    return email;
  }
 
  /** Set email */
  public void setEmail(String email) {
    this.email = email;
  }
 
  // MANY SIMILAR STRING-BASED SET/GET METHODS OMITTED
 
  /** Get adminPrivs */
  public boolean isAdminPrivileged(  ) {
    return adminPrivs;
  }
 
  /** Set adminPrivs */
  public void setAdminPrivileged(boolean adminPrivs) {
    this.adminPrivs = adminPrivs;
  }
 
  /** Return a String representation. */
  public String toString(  ) {
    return new StringBuffer("User[").append(name)
      .append(',').append(fullName).append(']').toString(  );
  }
 
  /** Check if all required fields have been set */
  public boolean isComplete(  ) {
    if (name == null || name.length(  )==0 ||
        email == null || email.length(  )==0 ||
        fullName == null || fullName.length(  )==0 )
      return false;
    return true;
  }
}

The only methods that do anything other than set/get are the normal toString( ) and isComplete( ) (the latter returns true if all required fields have been set in the bean). If you guessed that this has something to do with validating required fields in an HTML form, give yourself a gold star.

We can use this bean in a JSP-based web page just by saying:

<jsp:useBean id="myUserBean" scope="request" class="User">

This creates an instance of the class called myUserBean. However, at present it is blank; no fields have been set. To fill in the fields, we can either refer to the bean directly within scriptlets, or, more conveniently, we can use <jsp:setProperty> to pass a value from the HTML form directly into the bean! This can save us a great deal of coding.

Further, if all the names match up, such as an HTML parameter "name" in the form and a setName(String) method in the bean, the entire contents of the HTML form can be passed into a bean using property="*"!

<jsp:setProperty name="myUserBean" property="*"/>
</jsp:useBean>

Now that the bean has been populated, we can check that it is complete by calling its isComplete( ) method. If it's complete, we print a response, but if not, we direct the user to go back and fill out all the required fields:

<% // Now see if they already filled in the form or not...
  if (!myUserBean.isComplete(  )) {
%>
    <TITLE>Welcome New User - Please fill in this form.</TITLE>
    <BODY BGCOLOR=White>
    <H1>Welcome New User - Please fill in this form.</h2>
      <FORM ACTION="name_of_this_page.jsp" METHOD=post>
      // Here we would output the form again, for them to try again.      
      </FORM>
    <%    
    } else {
    String nick = newUserBean.getName(  );
    String fullname = newUserBean.getFullName(  );
// etc...
    // Give the user a welcome
    out.println("Welcome " + fullname);

You'll see the full version of this JSP in Program: JabaDot Web News Portal.

See Also

You can extract even more Java out of the JSP, making it look almost like pure HTML, by using Java custom tags. Custom tags (also called custom actions) are a new mechanism for reducing the amount of Java code that must be maintained in a JSP. They have the further advantage of looking syntactically just like elements brought in from an XML namespace, making them more palatable both to HTML editor software and to HTML editor personware. Their disadvantage is that to write them requires a greater investment of time than, say, servlets or JSP. However, you don't have to write them to use them; there are several good libraries of custom tags available, one from Tomcat and another from JRun. Sun is also working on a standard for a generic tag library. JSP tags are compiled classes, like applets or servlets, so any tag library from any vendor can be used with any conforming JSP engine. There are a couple of JSP custom tags in the source directory for the JabaDot program in Program: JabaDot Web News Portal.

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Next Pagearrow