JavaのBeanを利用した(JavaBeans)シンプルなアプリケーションを作成します。
コード (useinformationbean.jsp)
<%@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"/>
Beanのコード (InformationBean.java)
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;
}
}
コード (web.xml)
<?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プロパティへの代入動作について
messageプロパティへの参照や代入する動作にもかかわらず、getMessage()やsetMessage()メソッドが呼び出されるかについてですが、Javaではプロパティ名に対し
get(プロパティ名[先頭は大文字])
set(プロパティ名[先頭は大文字])
がゲッター、セッターとして定義されます。
message
というプロパティにアクセスできるように実装する場合はBean側に
getMessage()
setMessage()
の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側で追加した"!!!"が追加されて表示されることが確認できます。
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2011-02-12