编写一个servlet,实现统计网站被访问次数的功能。 步骤: 1.新建一个类ShowTimesServlet继承HttpServlet,重写doGet和doPost方法。 2.在doPost方法中调用doGet方法,在doGet方法中实现统计网站被访问次数的功能,用户每请求一次servlet,使访问次数times加1。 3.获取ServletContext,通过它的功能记住上一次访问后的次数。
时间: 2023-12-16 20:05:11 浏览: 23
以下是一个简单的实现统计网站被访问次数的servlet代码:
```
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import java.io.IOException;
public class ShowTimesServlet extends HttpServlet {
private int times = 0;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
Integer count = (Integer) context.getAttribute("count");
if(count == null) {
count = new Integer(0);
}
count = new Integer(count.intValue() + 1);
context.setAttribute("count", count);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("<html><head><title>访问次数统计</title></head>");
response.getWriter().println("<body><h1>网站被访问次数:" + count + "</h1></body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
在这个servlet中,我们使用了ServletContext的功能来存储网站被访问的次数。每次用户请求servlet时,我们获取ServletContext中存储的访问次数,并将其加1,然后再将新的访问次数存储回去。最后将访问次数显示在网页上。
注意,这个实现并不是线程安全的,如果多个用户同时访问该servlet,可能会导致访问次数计算错误。如果需要线程安全的实现,可以考虑使用synchronized关键字来保证同步。