我是servlet的新手。我的第一次尝试是编写一个简单的JSP-Application。哪个增量值是从0开始的值,也可以将其重新分配。
问题:
当我点击按钮"增加它"它会增加到1,当我再次点击同一个按钮时,值保持为1,但它应为2(在第二次点击时)
@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);
}
柜台型号:
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>
答案 0 :(得分:3)
问题在于您获取Counter
实例的方式
counter = (Counter) request.getAttribute("counter");
if (counter == null)
{
counter = new Counter();
}
此时您的计数器始终为null
,因为您是从request
对象获取的,这是每个传入请求的新实例。请求之间不会保留请求中设置的属性。
您要做的就是获取它并将其存储在会话中。
counter = (Counter) request.getSession().getAttribute("counter");
if (counter == null)
{
counter = new Counter();
request.getSession().setAttribute("counter", counter);
}
您应该在会话Serializable
public class Counter implements java.io.Serializable {
修改强>
正如@daiscog正确指出
<input type="hidden" name="counter" value="${counter}">
在您的JSP中不需要,因为您将在会话中存储计数器值。