JavaのBeanを利用した(JavaBeans)シンプルなアプリケーションを作成します。
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%-- Information オブジェクトを pageスコープとして作成 --%>
<jsp:useBean id="bean" scope="page" class="webApplication15.InformationBean"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>UseInformationBean</title>
</head>
<body>
<h1>UseInformationBean</h1>
<BR><HR><BR>
<OL>
<LI>
<%-- InformationBean オブジェクトにデータを格納 --%>
<!-- NO display -->
<jsp:setProperty> =
<I><jsp:setProperty name="bean" property="message"
value="Hello Information Bean" /></I>
<LI>
<%-- Informationbean オブジェクトからデータを取り出し --%>
<!-- Display -->
<jsp:getPeroperty> =
<I><jsp:getProperty name="bean" property="message"/> </I>
</OL>
</body>
</html>
useBeanディレクティブを用いbeanの利用を宣言します。
<jsp:useBean id="bean" scope="page" class="webApplication15.InformationBean"/>
setPropetyを利用しbeanのmessageプロパティに"Hello Information Bean"をセット(代入)します。
<jsp:setProperty name="bean" property="message" value="Hello Information Bean" />
getPropertyを利用しbeanのmessageプロパティを読み取り、その内容を画面に表示します。
<jsp:getProperty name="bean" property="message"/>
package webApplication15;
import java.io.*;
public class InformationBean implements Serializable{
private String message;
/** Creates a new instance of InformationBean */
public InformationBean() {
message = "No message specified";
}
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
messageプロパティにセットした内容が表示されることを確認できます。
messageプロパティへの参照や代入する動作にもかかわらず、getMessage()やsetMessage()メソッドが呼び出されるかについてですが、Javaではプロパティ名に対し
がゲッター、セッターとして定義されます。
の2つのメソッドを実装するとmessageプロパティでのアクセスの際にgetMessage()やsetMessage()が自動的に呼び出されます。
Benaのコードを以下に変更します。setMessageする際にBean側で"!!!"を追加します。
package webApplication15;
import java.io.*;
public class InformationBean implements Serializable{
private String message;
/** Creates a new instance of InformationBean */
public InformationBean() {
message = "No message specified";
}
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message + "!!!";
}
}
Bean側で追加した"!!!"が追加されて表示されることが確認できます。