Chapter 6. Creating JSP Components: JavaBeans

Today, you will learn how to create your own Java classes, as well as JavaBeans. As you develop your Java code, it'll get longer and longer, and after a while, it's not going to fit easily into scriptlets anymore. As it turns out, JSP servers are specially built to let your JSP pages interact with Java classes that you write yourself. Now that our applications are getting more involved, we're going to see how this works. Here's an overview of today's topics:

  • Creating and compiling Java classes

  • Creating Java methods

  • Using Java classes from JSP

  • Creating Java packages

  • Creating and using JavaBeans

  • Creating Bean properties

As we'll see, a JavaBean will give you access to properties and methods that you can use in JSP, called exposing. That is, today we're going to be working on the Java part of JavaServer Pages, and you're going to learn how to create compiled Java classes accessible from JSP.

Putting your code in compiled Java .class files is a good idea for several reasons. First, it enables you to organize your code and divide it into manageable components, which is especially important as your applications get more involved. Imagine trying to put twenty pages of Java code into a scriplet, for example—it's much easier to handle that code in its own Java file and interact with it as needed in JSP. The JSP server also has to compile those 20 pages of code each time you open the page, so that it also saves a great deal of time to compile your code first and save it in a Java .class file.

Tip

You'll see how to create Java classes directly in your JSP code (instead of Java source code files as we'll do today) in Day 8, “Handling Errors,” but note that such classes are intentionally kept short—for longer Java code, you usually use a JavaBean.

Creating components such as this is also how JSP supports code reuse. Whether you have, say, 10 different Web pages that use the same code to access a database, it's far more efficient to put that code into a component such as a JavaBean instead of having to repeat that code in each page. Because any number of Web pages can call the Java code in a JavaBean, JavaBeans provide us with components that allow us to reuse our code as needed.

Now that we're taking a closer look at Java programming, you'll also learn how to work with some Java utility classes today—the Date and Calendar classes, which enable you to work with and display dates and times, a very popular part of Web programming.

That's the program for today—creating Java components that can store your code and that you can interact with in JSP easily, as well as starting to take a look at some of the power available to us in the utility classes built into Java. Today we're going to write actual Java programs, compile them ourselves, and install them on the server, so that we can reach them in JSP. We'll take it step-by-step, and it all starts by creating a Java class.

Tip

For the official documentation on JavaBeans, see http://java.sun.com/products/javabeans/docs/.

Creating a Java Class

In this first example, you'll create a Java class named ch06_01 that will include a method named msg that will return the string "Hello from JSP!". We'll be able to call this method from JSP. To create a Java class, you use the Java class statement, which looks like this in general:

access class classname [extends ...] [implements ...] 
{
    [access] [static] type variable1;
        .
        .
        .
    [access] [static] type variableN;

    [access] [static] type method1 (parameter_list)
    {
        .
        .
        .
    }
    .
    .
    .
    [access] [static] type methodN (parameter_list)
    {
        .
        .
        .
    }
}

We'll get familiar with the parts of this statement in more detail in Day 11, “Creating More Powerful JavaBeans.” The access term specifies the accessibility of the class or class members to the rest of the program, and can be public, private, or protected. You use the extends and implements keywords with class inheritance, as we'll see in Day 11.

To create ch06_01.class, which is a compiled Java class file, you have to start with the actual Java code for this class, which you must store in a file named ch06_01.java. The class in this file will be named ch06_01, and you create it with the Java class statement:

public class ch06_01 
{
        .
        .
        .
}
Creating a Java Class

Let's get started on the actual Java code here, starting by adding a constructor to our class.

Creating a Constructor

You use a constructor to create an object from a class. In Java, a constructor is a method with the same name as the class itself, so that you can add a constructor to the ch06_01 class like this:

public class ch06_01 
{
    public ch06_01()
    {
    }
        .
        .
        .
}

Here, the code adds a method named ch06_01 to the ch06_01 class. This particular constructor doesn't do anything; it's a default constructor. Later today, you'll see how you can pass data to a constructor such as this to configure the object—in particular, you'll see how to use the constructor to set the text that the msg method will return. Now it's time to create the msg method.

Creating a Method

The msg method is simply supposed to return the text "Hello from JSP!", and you don't pass any data to it. This is a method of the ch06_01 class, so you can make its definition part of that class, as you see in Listing 6.1.

Example 6.1. Creating a Method (ch06_01.java)

public class ch06_01
{
    public ch06_01()
    {
    }

    public String msg()
    {
      return "Hello from JSP!";
    }
}

Note that this method is declared public. A public method such as this can be called from outside a class and any other classes based on this class. We have to make msg a public method so that it'll be accessible outside the ch06_01 class and we can call it from JSP.

That's all you need to start—you've created a public class, given it a default constructor, and added a method, msg, to it. The msg method will return our message when it's called, so let's take a look at calling that method from a JSP page now.

Compiling a Java Class

The first step in making the msg method accessible to our JSP code is to compile the file ch06_01.java, creating the file ch06_01.class. This is a step that the JSP server has been taking care of for us, but now that we want to compile a Java class, we'll handle this task ourselves.

In Day 1, “Getting Started!,” we set our computer's path to include the Java bin directory (such as C:jdk1.4in), which gives us access to the Java tools that we'll use here—in this case, we'll use the Java compiler, javac. Make sure that you're in the same directory as ch06_01.java, and enter javac ch06_01.java at the command prompt to compile ch06_01.java. For example, in Windows, that might look like

C:ch06>javac ch06_01.java 

Tip

If you haven't set your path as we discussed in Day 1, you can still use javac to compile Java files if you give the full path of that compiler, which might look like this in Windows: C:ch06>C:jdk1.4injavac ch06_01.java.

This will compile ch06_01.java and create ch06_01.class in the same directory. This new file, ch06_01.class, is the file we're going to need so that our JSP code can call the msg method.

Installing a Compiled Java Class

So where can we put ch06_01.class, so that we'll have access to it in a Web page? The examples for today go into the webappsch06 directory in the Tomcat directories. As we saw in Day 1, directories like the ch06 directory need a subdirectory named WEB-INF, which itself has two subdirectories, classes and lib:

webapps 
|____ch06
     |____WEB-INF
          |____classes
          |____lib

To give the JSP pages in the ch06 directory access to Java .class files, those .class files must go into the ch06WEB-INFclasses directory. That's all it takes to give your JSP code access to ch06_01.class—just put that file into the ch06WEB-INFclasses directory. Now we're ready to put this new Java class to work for us, and that's coming up next.

Using a Compiled Java Class

Our new Java class, ch06_01, is now installed—how do you use it in a Web page? You can start off by importing that class into our JSP page with the page directive (that you first saw in Day 1). The page directive's import attribute enables you to import a Java class to make it available to your JSP code. Here's how you can import the ch06_01 class:

<%@ page import="ch06_01" %> 
<HTML>
  <HEAD>
    <TITLE>Using a JavaBean</TITLE>
  </HEAD>
  <BODY>
        .
        .
        .
  </BODY>
</HTML>

Now you can create a new object of this class. This time the code will call this new object messager. This object will enable us to call the msg method to get the "Hello from JSP!" message:

<%@ page import="ch06_01" %> 
<HTML>
  <HEAD>
    <TITLE>Using a JavaBean</TITLE>
  </HEAD>
  <BODY>
    <H1>Using a JavaBean</H1>

    <% ch06_01 messager = new ch06_01(); %>
        .
        .
        .
  </BODY>
</HTML>

Now you have an object of the ch06_01 class, so you can call the msg method to get the message and display it, as you see in Listing 6.2.

Example 6.2. Calling a Method (ch06_02.jsp)

<%@ page import="ch06_01" %>
<HTML>
  <HEAD>
    <TITLE>Using a JavaBean</TITLE>
  </HEAD>
  <BODY>
    <H1>Using a JavaBean</H1>

    <% ch06_01 messager = new ch06_01(); %>

    The message is: <%= messager.msg() %>

  </BODY>
</HTML>

You can see the results in Figure 6.1, where our call to the msg method was successful.

Calling a compiled Java method.

Figure 6.1. Calling a compiled Java method.

At this point, we've been able to create and compile a Java class, install it where the JSP server can find it, and call a method in that class.

Calling a compiled Java method.

Creating a Package

Java provides an easy way of organizing your classes using Java packages. And if you use a Java package, you won't have to use the page directive to import your classes in JSP.

For example, you can put the Java code just developed into a new class that's part of a Java package. In this case, the package will be named beans. You can create this package in a .java file with the package statement, as you see in Listing 6.3.

Example 6.3. Creating a Package (ch06_03.java)

package beans;

public class ch06_03
{
  public String msg() {
    return "Hello from JSP!";
  }

  public ch06_03()
  {
  }
}

Now when you compile this new file, ch06_03.java, you'll get ch06_03.class—but the public class in this .class file is no longer ch06_03. Instead, it's beans.ch06_03, because it's in the beans package. That's how you must refer to it now—as beans.ch06_03. And you can't put it into the classes directory anymore; you must put it into a directory named classeseans:

webapps 
|____ch06
     |____WEB-INF
          |____classes
          |    |____beans
          |____lib

In this way, the disk organization of your Java classes reflects the package you've put your classes in. You separate package names with a dot (.). For example, if we created a package named these.are.my.beans like this

package these.are.my.beans; 

public class ch06_03
{
  public String msg() {
        .
        .
        .

then we'd store our ch06_03.class file in the directory classes hesearemyeans:

webapps 
|____ch06
     |____WEB-INF
          |____classes
          |    |____these
          |         |____are
          |              |____my
          |                   |____beans
          |____lib

Now that we've placed our new class in a package named beans, how do we access that class? That's coming up next.

Using a Package

As far as our JSP page goes, all that's changed is the name of our class; instead of ch06_03, it's now beans.ch06_03. That means all you have to do is use that as the class name, as you see in Listing 6.4.

Example 6.4. Using a Package (ch06_04.jsp)

<HTML>
    <HEAD>
        <TITLE>Using a Java Package</TITLE>
    </HEAD>

    <BODY>
        <H1>Using a Java Package</H1>

    <% beans.ch06_03 messager = new beans.ch06_03(); %>
    The message is: <%= messager.msg() %>

    </BODY>
</HTML>

Notice that the page directive we used in our earlier non-package example ch06_02.jsp is gone. Now that we've put our Java class into a package, the new directory structure (specifically, the beans subdirectory of the classes directory) tells Tomcat where to find ch06_03.class. We don't need to import any class at all; Tomcat will do that for us automatically. You can see the results in Figure 6.2—now we're organizing our Java classes into packages.

Using a class from a Java package.

Figure 6.2. Using a class from a Java package.

Passing Data to a Constructor

So far, our constructor hasn't done anything, but it's time to change that. Usually you use a Java class's constructor to configure an object when you create it, and we'll do that here. For example, we can pass the string we want the msg method to return to the constructor, storing that string internally.

Here's how it might look—in this case, the constructor for this class takes a String argument and stores it in an internal variable named msg. The msg method reads the text and returns it when you call this method; you can see how it all looks in Listing 6.5.

Example 6.5. Returning Text from a Method (ch06_05.java)

package beans;

public class ch06_05
{
    String msg;

    public ch06_05(String message)
    {
        msg = message;
    }

    public String msg() {
      return msg;
    }
}

Now you can pass data to this new constructor when you create a new object of this Java class, as you can see in Listing 6.6.

Example 6.6. Using a Constructor (ch06_06.jsp)

<HTML>
    <HEAD>
        <TITLE>Using a Constructor</TITLE>
    </HEAD>

    <BODY>
    <H1>Using a Constructor</H1>

    <% beans.ch06_05 messager = new beans.ch06_05("Hello from JSP!"); %>

    The message is: <%= messager.msg() %>
  </BODY>
</HTML>

And that's all there is to it—now you're able to configure the objects you create from Java classes with a constructor. You can see the results in Figure 6.3.

Using a constructor.

Figure 6.3. Using a constructor.

Actually, the Java classes we've been developing so far are not technically JavaBeans, they're just classes. A JavaBean must also expose properties.

JSP makes it easy to interact with Java classes and JavaBeans using the <jsp:useBean> element. You can use this element to create objects from JavaBeans (and then set and get property values using that object), and an in-depth look at this element is coming up next.

Using <jsp:useBean>

You've seen that you can create objects from Java classes without any special effort. But you can also use the <jsp:useBean> element to do the same thing. The <jsp:useBean> element is a convenience element in JSP that enables you to create an object of a Java class and give it an ID. You can then use that ID with two other elements, <jsp:getProperty> and <jsp:setProperty>, to get and set property values.

Let's take a look at the syntax of the <jsp:useBean> element. As discussed in the Introduction, this book uses the conventions of Java documentation for syntax such as this—here, | means “or,” items in bold are default settings, items in square brackets ([ and ]) are optional, and you must select one item of those that appear in curly braces ({ and } ):

<jsp:useBean id="ID" 
    scope="page|request|session|application"
{
    class="package.class" [ type="package.class" ]|
    beanName="{package.class | <%= expression %>}"
        type="package.class" |
    type="package.class"
}
{ /> | > other elements </jsp:useBean> }

Let's take a look at the attributes of this element:

  • id=”ID—. A variable that identifies the bean. You can use the variable name in expressions or scriptlets in the JSP page. If the bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used when the bean was created.

  • scope="page|request|session|application"—. The scope in which the bean exists. The default value is page. We'll see more on scope tomorrow. The page scope means you can use the bean within the JSP page. The request scope means you can use the bean from any JSP page processing the same request. The session scope means you can use the bean from any JSP page in the same session as the JSP page that created the bean, as you'll see tomorrow. The application scope means you can use the bean from any JSP page in the same application as the JSP page that created the bean, as you'll see tomorrow.

  • class="package.class"—. Creates a bean from a class. The class must have a public no-argument constructor.

  • type="package.class"—. If the bean already exists, this gives the bean a data type other than the class it was created from. The type must be a class or interface that the bean is already based on.

  • beanName=”{package.class | <%= expression %>}” type="package.class"—. Creates a bean from a class. When you use beanName, the bean is created by the java.beans.Beans.instantiate method, which we're not going to cover here.

  • other elements—. You can include other elements inside the body of <jsp:useBean>, such as the <jsp:getProperty> and <jspSetProperty> elements.

Here's an example that puts <jsp:useBean> to work. We've already seen this code, which creates an object from ch06_03.class and calls that object's msg method:

<% beans.ch06_03 messager = new beans.ch06_03(); %> 
The message is: <%= messager.msg() %>

Here's how to do the same thing with <jsp:useBean>. In this case, you can create a new bean with the ID bean1 from the same class, ch06_03.class (internally, Java actually uses the new operator to create this new object). Then you can refer to that bean with that ID—for example, you can call the bean's msg method as bean1.msg, as you see in Listing 6.7.

Example 6.7. Using a Bean (ch06_07.jsp)

<HTML>
    <HEAD>
        <TITLE>Using &lt;jsp:useBean&gt;</TITLE>
    </HEAD>

    <BODY>
    <H1>Using &lt;jsp:useBean&gt;</H1>

    <jsp:useBean id="bean1" class="beans.ch06_03" />

    The message is: <%= bean1.msg() %>
  </BODY>
</HTML>

You can see this Web page in Figure 6.4, where we've used <jsp:useBean> to create a new Java object.

Using the <jsp:useBean> element.

Figure 6.4. Using the <jsp:useBean> element.

The <jsp:useBean> element is designed to be used with two other elements—the <jsp:getProperty> and <jspSetProperty> elements, which enable you to work with bean properties. We'll look at how to create a property in a JavaBean next.

Creating a Read-Only Property

A property is a data item that you store in a JavaBean. For example, suppose you have a property named color. You can store various strings, such as red, blue, and so on in the color property, and the bean can use that property's value to configure the HTML it returns from other methods.

To support a JavaBean property, you use get and set methods. For example, for the color property, you'd add getColor and setColor methods to the bean. Note that you capitalize “color” in getColor and setColor, even though the actual property name is color—Java will expect these methods to exist, so it can work with the color property. If your property was named myFavoriteProperty, you would use the get and set methods getMyFavoriteProperty and setMyFavoriteProperty.

In this case, you can add a property named message that returns our message from the bean. You can start by only adding a get method, which means this property will be read-only (there's no set method to set its value). In particular, this code will enable Java to read the value of this property with a method named getMessage, as you see in Listing 6.8.

Example 6.8. Reading a Property Value (ch06_08.java)

package beans;

public class ch06_08
{

    private String message = "Hello from JSP!";

    public String getMessage()
    {
        return message;
    }

    public ch06_08()
    {
    }
}

Note that in addition to the getMessage method, the code has also declared a variable with the same name as the property, message. Java will expect to find a variable with the same name as the property this way, because that tells Java what the data type of the property is.

You might also note that the code has declared the string variable message to be private here. That means it's not accessible outside objects of this class—instead, you must access its value with the getMessage method. If you made this variable public instead (such as this: public String message = "Hello from JSP!";), you can access it in JSP code directly as object.message, as in this code:

<% beans.ch06_05 messager = new beans.ch06_08; %> 
The message is: <%= messager.message %>

However, this gives the JSP code direct access to the message variable, which means it can change that variable's value. To avoid such tampering, it has become standard in JavaBeans to use get and set methods to create a well-defined way of accessing property values—for example, if some JSP code tried to set a property named height to a negative value, the property's set method can detect that and not store that value in the property.

That's all we need to let Java read the value of this property. How do you read that value in JSP? You use the <jsp:getProperty> element.

<jsp:getProperty>: Getting a Property Value

You use the <jsp:getProperty> element to return the value of a property. Here's the syntax for this element:

<jsp:getProperty name="ID" property="propertyName" /> 

Here are the attributes of this element:

  • name=”ID—. This refers to the name of the bean as declared in a <jsp:useBean> element.

  • property="propertyName"—. The name of the bean property whose value you want. The property is declared as a variable in a bean and must have a corresponding get method.

Here's how you can use <jsp:getProperty> to get the value of the message property—all you have to do is use <jsp:useBean> to create an object named, say, bean1, and then get the value of the message property, as you see in Listing 6.9.

Example 6.9. Getting a Property Value (ch06_09.jsp)

<HTML>
    <HEAD>
        <TITLE>Getting a Property Value</TITLE>
    </HEAD>

    <BODY> element> element> element>
    <H1>Getting a Property Value</H1>

    <jsp:useBean id="bean1" class="beans.ch06_08" />

    The message is: <jsp:getProperty name="bean1" property="message" />
    </BODY>
</HTML>

You can see the results in Figure 6.5.

Getting a property's value.

Figure 6.5. Getting a property's value.

Now we can get the value of a property in a JavaBean. It's worth noting that you can also use <jsp:getProperty> inside a <jsp:useBean> element:

The message is: 
<jsp:useBean id="bean1" class="beans.ch06_08">
    <jsp:getProperty name="bean1" property="message" />
</jsp:useBean>

Note, however, that this will only work if the enclosing <jsp:useBean> element creates the object you're accessing with <jsp:getProperty>; if the object already exists (that is, was created by another <jsp:useBean> element), the elements in the <jsp:useBean> element are not executed.

That's how to get the value of a property—now what about setting a property's value?

Creating a Read/Write Property

To let Java set the value of a property, you can use a set method. For example, to let our JSP code set the message our bean will return, we can add a method named setMessage to set the value of the message property. You can see what that might look like in Listing 6.10.

Example 6.10. Creating a Property (ch06_10.java)

package beans;

public class ch06_10
{

    private String message = "Hello from JSP!";

    public void setMessage(String msg)
    {
        this.message = msg;
    }

    public String getMessage()
    {
        return this.message;
    }

    public ch06_10()
    {
    }
}

Note the keyword this here. In Java, this keyword always refers to the current object. In other words, this.message refers to the private variable message created and stored in this object:

private String message = "Hello from JSP!"; 

public void setMessage(String msg)
{
    this.message = msg;
}

The this keyword is a handy one to know now that you're creating Java objects—you can always use it in code to refer to the current object. As you've seen, it's not technically necessary to use the this keyword when you're referring to an object's data from code in that object (in fact, Java will use it automatically if you omit it), but you'll sometimes see it done for clarity. It can also prevent ambiguity when a function argument has the same name as a variable.

To actually set the value of the message property in JSP code, you can use the <jsp:setProperty> element.

<jsp:setProperty>: Setting Property Values

You use <jsp:setProperty> to set property values in JSP. You can pass your own values, or automatically pass values from the request object. Here's the syntax of this element:

<jsp:setProperty name="ID" 
{
   property="*" |
   property="propertyName" [ param="parameterName" ] |
   property="propertyName" value="{stringLiteral| <%= expression %>}"
}
/>

Here are the attributes of this element:

  • name=”ID—. The name of a bean that has already been created or located with a <jsp:useBean> element.

  • property=”*”—. Stores all of the values of request object parameters in bean properties. The names of the bean properties must match the names of the request parameters. Note that the request parameters are always strings, so Java converts them to the type of your property with methods such as Double.valueOf(String) automatically.

  • property="propertyName" [ param="parameterName" ]—. Sets one bean property to the value of one request parameter. If the bean property and the request parameter have different names, you must specify both property and param. If they have the same name, you can specify property and omit param.

  • property="propertyName" value=”{string | <%= expression %>}”—. Sets one bean property to a specific value. The value can be a String or an expression that is evaluated at runtime. If the value is a String, it is converted to the bean property's data type automatically.

Here's an example that puts <jsp:setProperty> to work using the set method setMessage that we've added to our example. In this case, we'll first display the default message that this property holds, and then use <jsp:setProperty> to set it to a new message, as you see in Listing 6.11.

Example 6.11. Setting a Property Value (ch06_11.jsp)

<HTML>
    <HEAD>
        <TITLE>Setting a Property Value</TITLE>
    </HEAD>

    <BODY>
        <H1>Setting a Property Value</H1>

        <jsp:useBean id="bean1" class="beans.ch06_10" />

        The message is: <jsp:getProperty name="bean1" property="message" />
        <BR>
       <jsp:setProperty name="bean1" property="message" value="Hello again!" />

       Now the message is: <jsp:getProperty name="bean1" property="message" />
    </BODY>
</HTML>

And that's all it takes—you can see the results in Figure 6.6, where we see that we were indeed able to set a bean's property.

Setting a property value.

Figure 6.6. Setting a property value.

Creating Private Methods

Here's one more thing we should note in passing. We've stored our property using a private variable in our Java code—doing so helps hide that data from external tampering. You can also create private methods that are purely internal to the current object, and cannot be called from outside the object. This is a good idea if you're using methods that you only want to call from inside the object. Such methods might help in performing internal calculations, for example. Using private methods can help organize your objects, wrapping up all their functionality into a self-contained entity.

Here's an example that shows how this works—in this case, you can just add a private method named privateMessage that will return the object's message, and call the method in the message property's get method, as you see in Listing 6.12.

Example 6.12. Using a Private Method (ch06_12.java)

package beans;

public class ch06_12
{

    private String message = "Hello from JSP!";

    public void setMessage(String msg)
    {
        this.message = msg;
    }

    public String getMessage()
    {
        return privateMessage();
    }

    private String privateMessage()
    {
        return this.message;
    }

    public ch06_12()
    {
    }
}

You can see a JSP page that uses this new class in Listing 6.13.

Example 6.13. Calling a Private Method (ch06_13.jsp)

<HTML>
    <HEAD>
        <TITLE>Calling a Private Method</TITLE>
    </HEAD>

    <BODY>
        <H1>Calling a Private Method</H1>

        <jsp:useBean id="bean1" class="beans.ch06_12" />

        The message is: <jsp:getProperty name="bean1" property="message" />
        <BR>
        <jsp:setProperty name="bean1" property="message" value="Hello again!" />

        Now the message is: <jsp:getProperty name="bean1" property="message" />
    </BODY>
</HTML>

You can see the results in Figure 6.7—now we've created private methods purely internal to a Java object.

Using private methods.

Figure 6.7. Using private methods.

Now that you're digging into the depths of Java, it's a good idea to take a look at the first of several Java utility classes that you'll see throughout the book. These utility classes are an important part of Java programming. Here you'll see the Date class, which is in the package named java.util.

Java Utility Classes: Working with Dates

The Date class enables you to create objects that represent a specific instant in time. This class is a popular one in Java programming among JSP programmers, because it enables you to keep track of dates and times. For example, you can see a JSP page that displays the date and time in Listing 6.14.

Example 6.14. Using the Date Class (ch06_14.jsp)

<HTML>
    <HEAD>
        <TITLE>Using the Date Class</TITLE>
    </HEAD>

    <BODY>
        <H1>Using the Date Class</H1>

        The date is: <%= new java.util.Date() %>.
    </BODY>
</HTML>

You can see the results in Figure 6.8.

Getting the date.

Figure 6.8. Getting the date.

Before Java version 1.1, you could also use the Date class to get the day of the month, year, hour, and so on separately, but that's gotten more complex. Now, the Calendar class should be used to get that kind of information. The original methods in the Date class are deprecated, as you'll see.

You should know that there are certain conventions used to represent months, days of the month, and so on, in the Date class:

  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so on, up to 11, which is December.

  • A date (day of month) is represented by an integer from 1 to 31.

  • An hour is represented by an integer from 0 to 23. The hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12, and so on.

  • A minute is represented by an integer from 0 to 59.

  • A second is represented by an integer from 0 to 61 (the values 60 and 61 do occur! But only for leap seconds).

You can see the Date class's methods in Table 6.1.

Table 6.1. Date Class Methods

Method

Does This

Date()

Creates a Date object and initializes it to the time it was created.

Date(int year, int month, int date)

Deprecated. Replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

Date(int year, int month, int date, hrs, int min)

Deprecated. Replaced by Calendar.set(year + int 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min).

Date(int year, int month, int date, hrs, int min, int sec)

Deprecated. Replaced by Calendar.set(year + int 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec).

Date(long date)

Creates a Date object and initializes it to the given number of milliseconds since January 1, 1970, 00:00:00 GMT.

Date(String s)

Deprecated. Replaced by DateFormat.parse(String).

boolean after(Date when)

Tests if this date is after the specified date.

boolean before(Date when)

Tests if this date is before the specified date.

Object clone()

Returns a copy of this object.

int compareTo(Date anotherDate)

Compares two Dates for ordering.

int compareTo(Object o)

Compares this Date to another object.

boolean equals(Object obj)

Compares two dates for equality.

int getDate()

Deprecated. Replaced by Calendar.get(Calendar.DAY_OF_MONTH).

int getDay()

Deprecated. Replaced by Calendar.get(Calendar.DAY_OF_WEEK).

int getHours()

Deprecated. Replaced by Calendar.get(Calendar.HOUR_OF_DAY).

int getMinutes()

Deprecated. Replaced by Calendar.get(Calendar.MINUTE).

int getMonth()

Deprecated. Replaced by Calendar.get(Calendar.MONTH).

int getSeconds()

Deprecated. Replaced by Calendar.get(Calendar.SECOND).

long getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

int getTimezoneOffset()

Deprecated. Replaced by Calendar.get(Calendar.ZONE_OFFSET) and Calendar.get(Calendar.DST_OFFSET).

int getYear()

Deprecated. Replaced by Calendar.get(Calendar.YEAR) - 1900.

void setDate(int date)

Deprecated. Replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date).

void setHours(int hours)

Deprecated. Replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours).

void setMinutes(int minutes)

Deprecated. Replaced by Calendar.set(Calendar.MINUTE, int minutes).

void setMonth(int month)

Deprecated. Replaced by Calendar.set(Calendar.MONTH, int month).

void setSeconds(int seconds)

Deprecated. Replaced by Calendar.set(Calendar.SECOND, int seconds).

void setTime(long time)

Sets this Date object to represent time milliseconds after January 1, 1970 00:00:00 GMT.

void setYear(int year)

Deprecated. Replaced by Calendar.set(Calendar.YEAR, year + 1900).

String toGMTString()

Deprecated. Replaced by DateFormat.format(Date date), using a GMT time zone.

String toLocaleString()

Deprecated. Replaced by DateFormat.format(Date date).

String toString()

Converts this Date object to a String.

long UTC(int year, int month, date, int hrs, int min, int sec)

Deprecated. Replaced by Calendar.set(year + int 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec), using a UTC time zone, followed by Calendar.getTime().getTime().

As you can see in Table 6.1, many of the Date class's methods that let you get the hour, day, minute, and so on are now deprecated in favor of the Calendar class. The reason is that the Date class wasn't prepared for internationalization. Using the Date class together with various Calendar classes, on the other hand, enables you to work with times in any international locale.

Date Class Methods
GregorianCalendar calendar = new GregorianCalendar(); 
Date date1 = new Date();
calendar.setTime(date1);
out.println("Calendar.YEAR is " + calendar.get(Calendar.YEAR) + "<BR>");

The fields of a class are its data members—that is, variables available publicly or to classes based on the current class. When a field name is in capital letters (like YEAR), that's a Java convention—it means the field is a constant, and its value can't be changed (these are static data members, and you declare them in Java with the static keyword). You can see the fields of the Calendar class in Table 6.2. You can also set the time in a GregorianCalendar object using the set method such as in the following, where the code is setting the time to 23:59 (one minute before midnight) on 11/31/2005:

calendar.set(2005, 11, 31, 23, 59); 

Table 6.2. Calendar Class Fields

Field

Meaning

int AM

Value of the AM_PM field for the period of the day from midnight to just before noon.

int AM_PM

Indicates whether the HOUR is before or after noon.

int APRIL

Value of the MONTH field for April.

int AUGUST

Value of the MONTH field for August.

int DATE

Use in get and set for the day of the month.

int DAY_OF_MONTH

Use in get and set for the day of the month.

int DAY_OF_WEEK

Use in get and set for the day of the week.

int DAY_OF_WEEK_IN_MONTH

Use in get and set for the number of the day of the week within the current month.

int DAY_OF_YEAR

Use in get and set for the day number within the current year.

int DECEMBER

Value of the MONTH field for December.

int DST_OFFSET

Use in get and set for the daylight savings offset in milliseconds.

int ERA

Use in get and set for the era (such as A.D. or B.C. in the Julian calendar).

int FEBRUARY

Value of the MONTH field for the second month of the year.

int FIELD_COUNT

The number of distinct fields recognized by get and set.

protected int[] fields

The field values for the currently set time for this calendar.

int FRIDAY

Value of the DAY_OF_WEEK field for Friday.

int HOUR

Use in get and set for the hour of the morning or afternoon.

int HOUR_OF_DAY

Use in get and set for the hour of the day.

protected boolean[] isSet

The flags that tell whether a specified time field for the calendar is set.

protected boolean isTimeSet

True if the value of time is valid.

int JANUARY

Value of the MONTH field for January.

int JULY

Value of the MONTH field for July.

int JUNE

Value of the MONTH field for June.

int MARCH

Value of the MONTH field for March.

int MAY

Value of the MONTH field for May.

int MILLISECOND

Use in get and set for the millisecond within the second.

int MINUTE

Use in get and set for the minute within the hour.

int MONDAY

Value of the DAY_OF_WEEK field for Monday.

int MONTH

Use in get and set for the month.

int NOVEMBER

Value of the MONTH field for November.

int OCTOBER

Value of the MONTH field for October.

int PM

Value of the AM_PM field for the period of the day from noon to just before midnight.

int SATURDAY

Value of the DAY_OF_WEEK field for Saturday.

int SECOND

Use in get and set for the second within the minute.

int SEPTEMBER

Value of the MONTH field for September.

int SUNDAY

Value of the DAY_OF_WEEK field for Sunday.

int THURSDAY

Value of the DAY_OF_WEEK field for Thursday.

long time

The currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.

int TUESDAY

Value of the DAY_OF_WEEK field for Tuesday.

int UNDECEMBER

Value of the MONTH field for the thirteenth month of the year.

int WEDNESDAY

Value of the DAY_OF_WEEK field for Wednesday.

int WEEK_OF_MONTH

Use in get and set for the week number within the current month.

int WEEK_OF_YEAR

Use in get and set for the week number within the current year.

int YEAR

Use in get and set for the year.

int ZONE_OFFSET

Use in get and set for the offset from GMT in milliseconds.

Here's an example putting these fields to work—you can find the current year, month, and so on and then reset the Calendar object to 23:59 on 11/31/2005 and display the various Calendar fields again, as you see in Listing 6.15.

Example 6.15. Using the Calendar Class (ch06_15.jsp)

<%@ page import="java.util.*" %>
<HTML>
    <HEAD>
        <TITLE>Fields of the Calendar Class</TITLE>
    </HEAD>

    <BODY>
        <H1>Fields of the Calendar Class</H1>
        <%
            String dateString = new String();

            GregorianCalendar calendar = new GregorianCalendar();
            Date date1 = new Date();
            calendar.setTime(date1);

            dateString += "Calendar.YEAR is " + calendar.get (Calendar.YEAR) + "<BR>";
            dateString += "Calendar.MONTH is " + calendar.get (Calendar.MONTH) + "<BR>";
            dateString += "Calendar.WEEK_OF_YEAR is " + calendar.get (Calendar
Using the Calendar Class (ch06_15.jsp).WEEK_OF_YEAR) + 
                "<BR>";
            dateString += "Calendar.WEEK_OF_MONTH is " + calendar.get (Calendar.WEEK_OF_MONTH)
                + "<BR>";
            dateString += "Calendar.DATE is " + calendar.get (Calendar.DATE) + "<BR>";
            dateString += "Calendar.DAY_OF_MONTH is " + calendar.get (Calendar.DAY_OF_MONTH) +
                "<BR>";
            dateString += "Calendar.DAY_OF_YEAR is " + calendar.get(Calendar.DAY_OF_YEAR) +
                "<BR>";
            dateString += "Calendar.DAY_OF_WEEK is " + calendar.get (Calendar.DAY_OF_WEEK) +
                "<BR>";
            dateString += "Calendar.DAY_OF_WEEK_IN_MONTH is "
                + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "<BR>";
            dateString += "Calendar.AM_PM is " + calendar.get(Calendar.AM_PM)  + "<BR>";
            dateString += "Calendar.HOUR is " + calendar.get(Calendar.HOUR)  + "<BR>";
            dateString += "Calendar.HOUR_OF_DAY is " + calendar.get (Calendar.HOUR_OF_DAY) +
                "<BR>";
            dateString += "Calendar.MINUTE is " + calendar.get(Calendar.MINUTE)  + "<BR>";
            dateString += "Calendar.SECOND is " + calendar.get(Calendar.SECOND)  + "<BR>";
            dateString += "Calendar.MILLISECOND is " + calendar.get (Calendar.MILLISECOND) +
                "<BR>";

            dateString += "Resetting the date!<BR>";

            calendar.set(2005, 11, 31, 23, 59);

            dateString += "Calendar.YEAR is " + calendar.get(Calendar.YEAR)  + "<BR>";
            dateString += "Calendar.MONTH is " + calendar.get(Calendar.MONTH) + "<BR>";
            dateString += "Calendar.WEEK_OF_YEAR is " + calendar.get (Calendar
Using the Calendar Class (ch06_15.jsp).WEEK_OF_YEAR) +
                "<BR>";
            dateString += "Calendar.WEEK_OF_MONTH is " + calendar.get (Calendar.WEEK_OF_MONTH)
                + "<BR>";
            dateString += "Calendar.DATE is " + calendar.get(Calendar.DATE)  + "<BR>";
            dateString += "Calendar.DAY_OF_MONTH is " + calendar.get (Calendar.DAY_OF_MONTH) +
                "<BR>";
            dateString += "Calendar.DAY_OF_YEAR is " + calendar.get (Calendar.DAY_OF_YEAR) +
                "<BR>";
            dateString += "Calendar.DAY_OF_WEEK is " + calendar.get (Calendar.DAY_OF_WEEK) +
                "<BR>";
            dateString += "Calendar.DAY_OF_WEEK_IN_MONTH is "
                + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "<BR>";
            dateString += "Calendar.AM_PM is " + calendar.get(Calendar.AM_PM)  + "<BR>";
            dateString += "Calendar.HOUR is " + calendar.get(Calendar.HOUR) + "<BR>";
            dateString += "Calendar.HOUR_OF_DAY is " + calendar.get (Calendar.HOUR_OF_DAY) +
                "<BR>";
            dateString += "Calendar.MINUTE is " + calendar.get(Calendar.MINUTE)  + "<BR>";
            dateString += "Calendar.SECOND is " + calendar.get(Calendar.SECOND)  + "<BR>";
            dateString += "Calendar.MILLISECOND is " + calendar.get (Calendar.MILLISECOND) +
                "<BR>";
            out.println(dateString);
        %>
    </BODY>
</HTML>

You can see the results in Figure 6.9, where you see the year, month, day, and so on.

Fields of the Calendar class.

Figure 6.9. Fields of the Calendar class.

Summary

Today you learned how to create Java classes, and JavaBeans that support properties.

In particular, you learned how to use the Java class statement to create Java classes. You also saw that you can place a constructor into a class, and that you can pass data to that constructor.

The <jsp:useBean> element enables you to create an object from a Java class or JavaBean. We've seen that you can use this element to name an object when it's created, so that it's accessible elsewhere in your code.

The <jsp:getProperty> element enables you to get the value of the property of a bean.

The <jsp:setProperty> element enables you to set the value of a bean's properties, including letting you set properties of the same name as request parameters automatically.

Finally, the Date class enables you to store dates and times. To access the individual day, month, year, and other fields in a Date object, you use a class based on the Calendar class, such as the GregorianCalendar class.

Q&A

Q1:

As a JSP programmer, do I need to use JavaBeans?

A1:

No. You can get along fine without them, but when your code gets past a certain size, it's awkward to store in a Web page. JavaBeans help you organize your code, and gives you easier access to Java directly.

Q2:

Can I use the request object in a JavaBean?

A2:

No, that object is not accessible in a JavaBean by default. However, you can pass the request object to a JavaBean if you set up a method in the bean to accept that object—see the Exercises for today.

Workshop

This workshop tests whether you understand all the concepts you learned today. It's a good idea to master today's concepts by honing your knowledge here before starting tomorrow's material. You can find the answers to the quiz questions in Appendix A.

Quiz

1:

What are two access specifiers you can use in Java classes?

2:

How do you invoke the Java compiler?

3:

What is the name of the directory in which you place .class files so that they're accessible from JSP?

4:

You can include <jsp:getProperty> and <jspSetProperty> elements inside a <jsp:useBean> element. Under what circumstances are those elements not executed?

5:

Why was the Date class deprecated?

Exercises

1:

Create a new JavaBean and pass the request object to a method of that bean (this object is an object of the Java javax.servlet.http.HttpServletRequest class). Using the request.getParameter method, recover some text from a text field and pass it back to a JSP page using another method, and display that text.

2:

Using Date and Calendar objects, put together a JSP page that displays the number of days remaining until your next birthday. (Hint: the DAY_OF_YEAR field will be useful here.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.254.192