@634

JSP

Advertisement

setProperty/getProperty/useBeanアクション

useBean : Bean(一定の基準を満たすJavaのクラス)を利用できるようにする。
<jsp:useBean id="Bean名" scope="有効範囲" class="Beanのクラス名" >
setProperty : Beanの変数に値を設定する。
<jsp:setProperty name="Bean名" property="プロパティ名" value="設定する値" >
getProperty : Beanから値を取得
<jsp:getProperty name="Bean名" property="プロパティ名" >
Beanの基準
  1. デフォルトコンストラクタがある。
  2. プロパティを参照するメソッドを持っている。
  3. パッケージングされている(推奨)
package sample;    // パッケージ

public class SampleBean{
    private int num;    // プロパティ
    public SampleBean(){num = 0;} // デフォルトコンストラクタ
    public void setNum(int n){num = n;}    // プロパティ設定用メソッド
    public int getNum(){return num;}    // プロパティ取得用メソッド
}
プロパティアクセス用メソッド:setXXX getXXX
プロパティがbooleanの場合:setXXX isXXX

setProperty/getProperty/useBeanサンプル

useBean.jsp
<%@ page contentType="text/html; charset=Shift_JIS" %>
<meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS">
<html lang="ja">
<head>
<title>テスト</title>
</head>
<body>
<jsp:useBean id="profile" scope="page" class="model.Profile" />
<h1>useBean, setProperty, getProperty</h1>


<%
    if(request.getParameter("submit") != null){
        String name = request.getParameter"name");
        int age = Integer.parseInt(request.getParameter("age"));
%>
        <%-- 値の設定 --%>
        <jsp:setProperty name="profile" property="name" value="<%= name %>" />
        <jsp:setProperty name="profile" property="age" value="<%= age %>" />
<%
    }
%>
<p>

現在の値<br>
name : <jsp:getProperty name="profile" property="name" />
age :<jsp:getProperty name="profile" property="age" />
</p>


<form method="post" action="./useBean.jsp">
NAME <input type="textbox" name="name"><br>
AGE <input type="textbox" name="age"><br>
<input type="submit" name="submit" value="???M">
</form>

</body>
</html>
Profile.java
package model;

public class Profile{
    private String name;
    private int age;

    public Profile(){
        name = "???";
        age = 0; 
    }

    public void setName(String s){
        name = s;
    }

    public String getName(){
        return name;
    }

    public void setAge(int i){
        age = i;
    }

    public int getAge(){
        return age;
    }

}
実行結果サンプル
(略)
現在の値
name : Tom
age :15
(略)

Advertisement

ショートカット

634
634ブログ
このカテゴリのトップページに戻る
Incubator(Pukiwiki)
634ラボ
   UIコレクションギャラリー
   ZO-3ジェネレーター

サイト検索


Y!ログール