Reputation: 147
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:
when I click on the button "Increment it" it gets increment to 1, when I click again on the same button, the value stays 1, but it should be 2 (on second click)
@WebServlet("/countServlet")
public class CounterServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
Counter counter;
counter = (Counter) request.getAttribute("counter");
if (counter == null)
{
counter = new Counter();
}
String increment = request.getParameter("increment");
if (increment != null)
{
counter.increment();
}
String reset = request.getParameter("decrement");
if (reset != null)
{
counter.decrement();
}
request.setAttribute("counter", counter.getCounter());
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
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
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