编写一个servlet,实现统计网站被访问次数的功能。步骤:1.新建一个类ShowTimesServlet继承HttpServlet,重写doGet和doPost方法。
时间: 2024-01-21 20:18:24 浏览: 99
实验3 Servlet基础.docx
好的,以下是实现统计网站被访问次数的ShowTimesServlet代码:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ShowTimesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Integer count = (Integer) session.getAttribute("count");
if (count == null) {
count = 1;
} else {
count++;
}
session.setAttribute("count", count);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>网站被访问次数统计</title></head>");
out.println("<body>");
out.println("<h1>网站被访问次数统计</h1>");
out.println("<p>您是第 " + count + " 位访问者。</p>");
out.println("</body></html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
```
这个servlet会在客户端第一次访问时创建一个session,并将count值初始化为1。之后每次请求都会取出session中的count值,加1后再存回session中,最后输出当前网站被访问的次数。需要注意的是,每个客户端访问时都会创建一个session,因此这个统计方式并不精确,但在大多数情况下已经足够使用了。
阅读全文