user2133606
user2133606

Reputation: 347

jsp web application - each time button is clicked, increase number by 1

the application has a button and starts with the number 0, and each time the button is clicked on, the integer is increased by 1.

the problem is I have to incorporate it with this code and covert string "0" to integer 0

<%
    int x = 0;
    try { x = Integer.parseInt("0"); }
    catch (Exception e) { x = 0; }
%>

also how would I continue to stay on the same page to click on the button to add one (do I put the code within the html?)

this is what I have so far:

<html>
    <body>
        <form method="post" action="index.jsp" />

            <% 
                String integer = request.getParameter("0"); 
            %>

            <%
                int x = 0;
                try { x = Integer.parseInt("0"); }
                catch (Exception e) { x = 0; }
            %>

            <input type="text" name="integer" value="<%=integer%>"/>
            <input type="submit" value="submit" />

        </form>
    </body>
</html>

Upvotes: 1

Views: 5574

Answers (1)

This is the code that would work for that situation.

<%! int clicks = 0; %>

<%
    String param = request.getParameter("integer");

    try
    {
       int i = Integer.parseInt(param);

       clicks ++;
    } 
    catch (NumberFormatException e)
    {
    }
%>
<p>Number of clicks untill now: <%= clicks %> </p>

<form action="">
    <input type="text" name="integer" value="1"/>
    <input type="submit" value="submit" />
</form>

You had some mistakes:

  • You are not using a form tag
  • You name your parameter "integer" but you are trying to recover it using the name of "0"

Some guidelines for you:

  • If you want to increase the value without reloading the page you need javascript/ajax.
  • You shouldn't be adding scriptlets to your JSP pages. Insted you should code a Servlet which handles the click increase and uses a RequestDispatcher to send to a JSP page where you are showing it (and not doing any calculations).

EDIT: I should warn you that this code would show the click value for every user on the page. If you don't want that, you should remove de JSP declaration and work with the param request instead. From my code it should be easy for you.

Upvotes: 1

Related Questions