I have an input form (index.jsp):
<form action="process-mobile-number.jsp" method="post">
<table>
<tr>
<td>Enter a mobile number:</td>
<td>
<input type="number" name="telco" maxlength="4" style="width: 20%" required title="Please enter your 4-digit prefix."/>
-
<input type="text" name="mobile" maxlength="7" style="width: 70%" required title="Please enter your 7-digit number."/>
</td>
</tr>
<tr><td><input type="submit" value="Submit" style="width: 50%"/></td></tr>
</table>
</form>
This is the servlet that keeps count on how many times the system has been used:
@WebServlet("/process-mobile-number.jsp")
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
...
// initialize counters
int smartCtr = 0;
int globeCtr = 0;
int sunCtr = 0;
...
switch(telcoProvider) {
case "SMART":
smartCtr++;
break;
case "GLOBE":
globeCtr++;
break;
case "SUN":
sunCtr++;
break;
}
...
// assemble counter bean
Counter counter = CounterAssembler.getInstance(smartCtr, globeCtr, sunCtr);
// create session
HttpSession session = request.getSession();
// bind objects to session
session.setAttribute("smartCtr", counter.getSmartCtr());
session.setAttribute("globeCtr", counter.getGlobeCtr());
session.setAttribute("sunCtr", counter.getSunCtr());
// redirect to results jsp
response.sendRedirect("mobile-number-result.jsp");
}
This is the output JSP:
<form action="index.jsp" method="post">
<table>
...
<tr><td style="font-weight: bold">Your number of successful attempts are:</td></tr>
<tr><td>SMART: <%=session.getAttribute("smartCtr") %></td></tr>
<tr><td>GLOBE: <%=session.getAttribute("globeCtr") %></td> </tr>
<tr><td>SUN: <%=session.getAttribute("sunCtr") %></td></tr>
<tr>
<td>
<input type="hidden" name="smartctr" value="<%=session.getAttribute("smartCtr") %>"/>
<input type="hidden" name="globectr" value="<%=session.getAttribute("globeCtr") %>"/>
<input type="hidden" name="sunctr" value="<%=session.getAttribute("sunCtr") %>"/>
<input type="submit" value="Go Back" style="width: 18%"/>
</td>
</tr>
</table>
</form>
QUESTION:
However, when I press "Go Back" to return to index.jsp and begin another transaction, the counters are always reset to 0.
How do I make them persist with the hidden form fields?
Thank you.
Because each time your dopost method is called, you're initializing variable with value 0. Instead simply you can check if the session attribute exist, else set the attribute.
If you want to count number times the of system usage, I suggest you should use static variable.