Servlet重置按钮

时间:2013-06-09 13:52:52

标签: servlets

每次访问我的页面时都有一个点击计数器servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleCounter extends HttpServlet{
  int counter = 0;
  public void doGet(HttpServletRequest request, HttpServletResponse
    response)throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  counter++;
  pw.println("the number of times this page was visited:" + counter);
  }
}

点击计数器的上述部分有效,但我想添加一个重置按钮。

我在考虑一个表单中的按钮,它将使用post并返回同一页面并再次设置int counter = 0。如何在底部修复此部分或添加重置按钮的权利是什么?

pw.println("<form action="counter.java" method="post"> <input type="submit" value="reset"></form>");

1 个答案:

答案 0 :(得分:0)

不需要formpost请求,只需使用get请求,使用简单的anchor和请求参数reset即可应重置计数器reset=true

以下是doGet方法的外观:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter pw = response.getWriter();
    // check if this is a request to reset the counter
    if(Boolean.valueOf(request.getParameter("reset"))) {
        counter = 0;
        // redirect to the same servlet so that you don't have the reset parameter
        // in url bar to avoid accidently resetting the counter on a refresh 
        response.sendRedirect(getServletContext().getContextPath() +
            request.getServletPath());
    } else {
        counter++;
        pw.println("<html><head/><body>");
        pw.println("<span>the number of times this page was visited:" + counter + "</span>");
        // anchor with the parameter reset=true
        pw.println("<a href=\"" + 
            getServletContext().getContextPath() + 
            request.getServletPath() + 
            "?reset=true" + "\">reset counter</a>");
        pw.println("</body></html>");
    }
}