0

数字とボタンがある JSP プログラムを実行しようとしています。ボタンをクリックすると、上記の数値が増加します。このプログラムでセッションを使用する必要があります。

これは私がしたコードです:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome </title>
</head>

<body>

<%
    // check if there already is a "Counter" attrib in session  
    AddCount addCount = null;
    int test = 0;
    String s;

    try {
        s = session.getAttribute("Counter").toString(); 

    } catch (NullPointerException e){
        s = null;
    }

    if (s == null){ 
        // if Counter doesn't exist create a new one

        addCount = new AddCount();
        session.setAttribute("Counter", addCount);

    } else {
        // else if it already exists, increment it
        addCount = (AddCount) session.getAttribute("Counter");
        test = addCount.getCounter();
        addCount.setCounter(test); 
        addCount.addCounter(); // increment counter
        session.setAttribute("Counter", addCount);
    }

%>

<%! public void displayNum(){ %>
        <p> Count: <%= test %> </p>
<%! } %>

<input TYPE="button" ONCLICK="displayNum()" value="Add 1" />

</body>
</html>

その結果、プログラムを実行するたびに数値が増加します..しかし、これが発生するのは望ましくありません..ボタンをクリックすると数値が増加するようにします:/何が間違っていますか?

助けてくれてありがとう。よろしくお願いします!

4

1 に答える 1

1

実行できたはずのスキーマ JSP。

ここでは、ページの名前が「counter.jsp」で、AddCount クラスがパッケージ「mypkg」にあると想定しています。

JSP エンコーディングは、最初の HTML ブラウザー テキストの前の HTML ヘッダー行に設定できます。

ISO-8859-1 の場合、実際にはエンコーディング Windows-1252 を使用できますが、特別なコンマのような引用符などの追加の文字が含まれます。MacOS ブラウザーでさえ、これらを受け入れます。

ここでは、フォーム パラメーター「somefield」が存在するかどうかとして、ボタンがクリックされたかどうかを確認します。(他の可能性もあります。)

ここではsession="true"が重要です。

<%@page contentType="text/html; charset=Windows-1252"
        pageEncoding="Windows-1252"
        session="true"
        import="java.util.Map, java.util.HashMap, mypkg.AddCount" %>
<%
    // Check if there already is a "Counter" attrib in session  
    AddCount addCount = (AddCount)session.getAttribute("Counter"); 
    if (addCount == null) { 
        // If Counter doesn't exist create a new one
        addCount = new AddCount();
        session.setAttribute("Counter", addCount);
    }

    // Inspect GET/POST parameters:
    String somefield = request.getParameter("somefield");
    if (field != null) {
        // Form was submitted:

        addCount.addCounter(); // increment counter
    }

    int count = addCount.getCounter();
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Welcome - counter.jsp</title>
    </head>

    <body>
        <p> Count: <%= count %></p>
        <form action="counter.jsp" method="post">
            <input type="hidden" name="somefield" value="x" />
            <input type="submit" value="Add 1" />
        </form>
    </body>
</html>
于 2012-12-18T22:10:43.070 に答える