2012-12-15 103 views
0

嗨我想做一个JSP程序,其中显示一个数字和一个按钮。当用户点击这个按钮时,它的数字会增加。我想在这个程序中包含会话。会话JSP按钮点击

我所做的是这样的:

这是HTML表单:

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

<%! public void displayNum(){ %> 
Number: <%=session.getAttribute("Counter") %> 
<%! } %> 

<FORM METHOD=POST ACTION="getcount.jsp"> 
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button> 
</FORM> 

</body> 
</html> 

,这是myJSP文件:

<% 
    AddCount addCount = new AddCount(); 
    addCount.setCounter(addCount.addCounter(addCount.getCounter())); 
    int counter = addCount.getCounter(); 

    session.setAttribute("Counter", counter); 
%> 

AddCou nt是一个带有可变计数器,setter和getter的java类,还有一个用于增加counter-addCount(num)的函数;我在运行文件时得到的所有内容都是一个没有任何文本的按钮:/

我一直在尝试一遍又一遍。有人能帮助我吗?

谢谢!

回答

1

您正在HTML中添加java代码,这是不可能的。

第二件事,即使你在AddCount中有一个静态int计数器,它也不会工作,因为许多用户可能会使用这个页面,并且期望每次点击只有一个增量。

所以,你应该做的是写一个jsp文件中像这样的index.jsp

<%Integer counter = (Integer)request.getSession().getAttribute("counter") 
    if(counter==null) {counter=0;} 
    counter ++; 
    request.getSession().setAttribute("counter",counter); 

%> 
<div>counter=<%=counter%></div><br> 
<a href="index.jsp">+1</a> 
0
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>My Form</title> 
</head> 
<body> 

function displayNum() 
{ 

<% 
    AddCount addCount = new AddCount(); 
    addCount.setCounter(addCount.addCounter(addCount.getCounter())); 
    int counter = addCount.getCounter(); 

    session.setAttribute("Counter", counter); 
%> 

document.getElementById("demo").innerHTML="<%=session.getAttribute("Counter")%>"; 
} 

<p id="demo"> {number will be displayed here} </p> 
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button> 

</body> 
</html> 
+0

我尝试这样做..但当我运行它时,我只得到1号,没有按钮!感谢您的帮助btw – Bernice

+0

尝试使用jQuery ajax,我已经添加到下一个答案。 –

0
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <script src="jquery.js"></script> 
    <title>My Form</title> 
    </head> 
    <body> 

    <script> 
     $(document).ready(function() { 
      $("button").click(function() { 
       $("#div1").load("increament.jsp"); 
      }); 
     }); 
    </script> 

    <div id="div1"> {number will be displayed here} </div> 
    <button>Add 1</button> 

    </body> 
    </html> 

和increament.jsp文件:

<% 
    int count; 
    if (session.getAttribute("Counter") == null) { 
     count = 1; 
    } else { 
     count = (Integer) session.getAttribute("Counter"); 
     count++; 
    } 
    session.setAttribute("Counter", count); 
    out.println(session.getAttribute("Counter")); 
%>