2012-12-15 102 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")); 
%>