====== JSP and Java Beans ======
===== Java Beans: A Quick Intro =====
A Java Bean is a class that meets the following requirements:
- It must have a 0-ary constructor (i.e. parameterless).
- It should not have any public instance variables.
- Values of class instance variables visible/accessible to other classes should follow naming conventions.
* Accessor methods should be named, getXxx and setXxx, where xxx (no case) is the name of the instance variable. Xxx is called the property of the object. For example, in the java.util.Date class, the variable (or property) hours is accessed by a method called, getHour().
* Boolean variables are to be accessed using the method, isXxx.
All standard Java classes can be used as beans.
===== Using beans in JSP Pages =====
Example
<%@ page language="java" contentType="text/html" %>
JSP: Beans Example 1
JSP: Example of using a Bean
The current date and time is:
- Date:
- Month:
- Year:
- Hours:
- Minutes:
===== Accessing Bean properties =====
===== Setting Bean Properties =====
Example Bean
package ecom;
public class SecretMessage {
private String message = "No message.";
public String getMessage() {
return message;
}
public void setMessage(String s) {
message = s;
}
}
===== Using the SecretMessage Bean =====
Using the SecretMessage Bean
Using the Secret Message Bean
- Initial Message (using getProperty):
-
Secret message (after setting):
EXERCISE
Enter the code above and try it. You will need to compile the bean class and place it in the appropriate place for you server. For example, Apache Tomcat requires it to be in the directory
install_dir/webpages/WEB-INF/classes/ecom/SecretMessage.class
Another example of using the SecretMessage bean.
Using the SecretMessage Bean version 2
Using the Secret Message Bean (Version 2)
- Initial Message:
-
Secret message:
EXERCISE
Enter the code above in a file called Bean2.jsp and try it using the following URL:
* http://server.address/youraccount/Bean2.jsp?Message=Rendezvous+at+10
Parameter values (as in form input) can also use the syntax:
EXERCISE
Replace the line in Bean2.jsp to use the above.
For multiple parameters that are matched one-to-one with bean properties, you can also use the syntax:
===== Further Information / External Links =====
* Core Servlets and Java Server Pages, Marty Hall, Prentice Hall, 2000.
* Java Server Pages, Hans Bergsten, O'Reilly, 2001
* A JSP Tutorial from SUN (http://java.sun.com/products/jsp/docs.html)