编写一个servlet,实现统计网站被访问次数的功能 新建一个类ShowTimesServlet继承HttpServlet,重写doGet和doPost方法
时间: 2024-01-21 10:16:59 浏览: 126
好的,下面是一个简单的实现:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ShowTimesServlet")
public class ShowTimesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private int count = 0;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
count++;
response.getWriter().append("This website has been visited ").append(String.valueOf(count)).append(" times.");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
这个servlet会在每次GET请求时将访问次数加1,并返回一个包含当前访问次数的字符串。你也可以将访问次数保存在文件或数据库中,以便重启服务器后能够恢复访问次数。
阅读全文