15. Servlet入门 - 统计网站被访问的总次数
需求
- 在页面中显示您是第x位访问的用户.
思路分析
image-20191208160926430
代码实现
1.CountServlet 实现 count 总次数在 ServletContext 的 计数
image-20201228005843990
代码语言:javascript复制@WebServlet(name = "CountServlet", value = "/count")
public class CountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 读取Servlet中的count参数
ServletContext servletContext = getServletContext();
Object count = servletContext.getAttribute("count");
//2. 判断count参数是否存在,如果不存在,则初始化,设置为0;反之,加 1
if (count == null) {
count = 0;
servletContext.setAttribute("count", count);
}
int number = (int) count 1;
System.out.println("number: " number);
servletContext.setAttribute("count", number);
//3.返回浏览器 Welcome
response.getWriter().write("Welcome...." number);
}
}
启动 tomcat 服务,访问测试如下:
http://localhost:8080/demo01/count
image-20201228005910378
2.ShowServlet 实现读取 ServletContext 的 count 总计数
image-20201228010038457
代码语言:javascript复制@WebServlet(name = "ShowServlet", value = "/show")
public class ShowServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 读取ServletContext中的count总次数
ServletContext servletContext = getServletContext();
int count = (int)servletContext.getAttribute("count");
// 2. 返回浏览器访问的总次数
response.setContentType("text/html; charset=UTF-8"); // 设置浏览器以utf8编码格式,不然中文显示为乱码
response.getWriter().print("您是第 " count " 位访问的用户");
}
}
访问 http://localhost:8080/demo01/show 测试如下:
image-20201228010109220