1

Web アプリケーションで mvc struts フレームワークを使用しています。scriletsを使用してjspページにデータベースから動的な値を表示していますが、<% %> その方法は悪い習慣でしたが、スクリプトレットなしでそれを行う方法のリンクをたどりましたが、あまり理解できません..私はストラットを使用しており、アクションとBeanクラスがありますこれは私のjspページ

<%@page import="java.sql.ResultSet"%>
<%@page import="com.pra.sql.SQLC"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<table align="left" width="346" border="0">
    <tr><td align="center" colspan="2" style="font-size:20px;">Tests We Provide</td></tr>
    <tr>
        <th width="194" height="52" align="left" nowrap>Test Name</th>
        <th width="142" align="left" nowrap>Test Fee</th>
    </tr>
    <%
        String sql = "Select tname,tfee from addtest order by tname";
        ResultSet rs = SQLC.getData(sql, null);
        while (rs.next()) {
            String testname = rs.getString("tname");
            String testfee = rs.getString("tfee");
    %>
    <tr>
        <td width="194" height="30" nowrap><%=testname%></td>
        <td width="142" nowrap><%=testfee%></td>
    </tr>  
    <%
        }
    %>
</table>

Formbean でコードを記述してテスト名と料金を表示し、Bean から JSP に各値を 1 つずつ取得する方法を教えてください。スクリプトレットを使用せずにこれを行う方法を教えてください。 )

4

1 に答える 1

1

データベースの読み取りコードをアクションコントローラーに移動します。db から必要な値を読み取り、それをリクエストまたはモデルに入れる必要があります。

jstl を使用して値を (jsp で) 出力するよりも:

<c:out value="${parameterFromRequest}"/>

Bean を定義します。

public class MyBean {
    private final String tName;
    private final String tFee;

    public MyBean(String tName, String tFee) {
        this.tName = tName;
        this.tFee = tFee;
    }

    public String getTName() {
        return tName;
    }

    public String getTFee() {
        return tFee;
    }
}

アクション コントローラーでコレクションを作成します。

String sql = "Select tname,tfee from addtest order by tname";
ResultSet rs = SQLC.getData(sql, null);
Collection<MyBean> myBeans = new ArrayList<MyBean>();
while (rs.next()) {
    String testname = rs.getString("tname");
    String testfee = rs.getString("tfee");
    myBeans.add(new MyBean(testname, testfee));
}

request.setAttribute("myBeans", myBeans);

jsp でのアクセス:

<c:forEach var="myBean" items="${myBeans}">
    Name: <c:out value="${myBean.tName}"/>
    Fee: <c:out value="${myBean.tFee}"/>
</c:forEach>
于 2012-05-23T06:04:51.640 に答える