0

I have a hit counter servlet for each time my page is visited

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);
  }
}

The part above for the hit counter works but i want to add a reset button.

I was thinking of a button in a form that will use post and go back to the same page and set the int counter = 0 again. how can i fix this part on the bottom or what is the right to add a reset button ?

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

1 回答 1

0

不需要一个form和一个post请求,只需使用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>");
    }
}
于 2013-06-09T14:37:26.397 回答