我正在尝试做一个有数字和按钮的 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>
结果是每次我运行程序时,数字都会增加..但是我不希望这种情况发生..我希望数字在单击按钮时增加:/我做错了什么?
谢谢你的帮助。将不胜感激!