Matej
Matej

Reputation: 147

Increment/Decrement a value with JSP/Servlet

I'm new with servlets. And my first try was to write a simple JSP-Application. Which increments are value starting with 0, and also possible to drecrement it.

Problems:

Counter model:

public class Counter {

    private int counter = 0;

    public void increment() {
        counter++;
    }

    public void decrement() {
        counter--;
    }

    public void reset() {
        counter = 0;
    }

    public int getCounter() {

        return counter;
    }
}

JSP:

<title>Counter</title>
</head>
<body>

The current state of the counter:  ${counter}

<form action="countServlet" method="GET">
<input type="submit" name="increment" value="Increment it">
<input type="submit" name="decrement" value="Decrement it">
<input type="hidden" name="counter" value="${counter}">
</form>

Upvotes: 1

Views: 3965

Answers (1)

George Lee
George Lee

Reputation: 826

The problem is to do with the way you are getting your Counter instance

counter = (Counter) request.getAttribute("counter");
if (counter == null)
{
    counter = new Counter();
}

Your counter will always be null at this point because you are getting it from the request object which is a new instance for each incoming request. Attributes set on the request are not persisted between requests.

What you want to do is get it and store it on the session.

counter = (Counter) request.getSession().getAttribute("counter");
if (counter == null)
{
    counter = new Counter();
    request.getSession().setAttribute("counter", counter);
}

You should make any object that you are storing on the session Serializable

public class Counter implements java.io.Serializable {

EDIT:

As @daiscog correctly points out the

<input type="hidden" name="counter" value="${counter}">

in your JSP in not need as you will be storing the counter value in the session.

Upvotes: 3

Related Questions