2012-12-18 41 views
0

我想做一個JSP程序,其中有一個數字和一個按鈕。點擊該按鈕後,上面的數字會增加。我需要在這個程序中使用會話。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> 

的結果是,我每次運行程序時,該數目的增量。但是我不希望這種事情發生。我想數量遞增點擊按鈕:/我在做什麼錯了?

感謝您的任何幫助。將非常感謝!

+0

你從哪裏瞭解到JSP和HTML/JS?你將JSP和JS混爲一談(並且使用oldschool 90的HTML樣式和較高的屬性名稱,還使用oldschool 00的JSP * scriptlets *)。你確定你正在閱讀關於這個主題的正確教程嗎? – BalusC

+0

從這個網站:http://www.jsptut.com/Sessions.jsp:/有沒有更好的?我不知道我真的很困惑..這是JSP和哪個是JS:/我不知道從哪裏開始真的:/ – Bernice

+0

我在哪裏在這裏使用JS? :/ – Bernice

回答

1

原理圖JSP,因爲它可能已經完成。

這裏我假設頁面被命名爲「counter.jsp」,並且AddCount類駐留在一個包「mypkg」中。

可以在第一個HTML瀏覽器文本之前的HTML標題行中設置JSP編碼。

對於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> 
+0

非常感謝您的回答..真的幫助了我! :) – Bernice