数字とボタンがある 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>
その結果、プログラムを実行するたびに数値が増加します..しかし、これが発生するのは望ましくありません..ボタンをクリックすると数値が増加するようにします:/何が間違っていますか?
助けてくれてありがとう。よろしくお願いします!