您的位置:首页 > 运维架构 > 网站架构

Servlet网站访问量统计小案例

2016-01-19 14:56 465 查看

Servlet网站访问量统计小案例

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse res)
throws ServletException, IOException {
/*
* 1. 获取ServletContext对象
* 2. 从ServletContext对象中获取名为count的属性
*   3. 如果存在:给访问量加1,然后再保存回去;
*   4. 如果不存在:说明是第一次访问,向Servletcontext中保存名为count的属性,值为1
*/
ServletContext application = this.getServletContext();
Integer count = (Integer) application.getAttribute("count");
if (count == null) {
application.setAttribute("count", 1);
} else {
application.setAttribute("count", count+1);
}
res.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
/*
* 向浏览器输出
*   需要使用响应对象!
*/
System.out.println("本网站访问量:"+count+"人");
PrintWriter out = res.getWriter();
out.print("本网站访问量:" + count + "人");
out.flush();
out.close();
}

}


web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlet03</display-name>
<servlet>
<servlet-name>AServlet</servlet-name>
<servlet-class>com.servlet.AServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>AServlet</servlet-name>
<url-pattern>/AServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: