package com.zdsofe.servlet1; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class CountVisited
*/
@WebServlet("/CountVisited")
public class CountVisited extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//编码格式
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//输出流
PrintWriter out=response.getWriter();
//获得上下文环境
ServletContext context= request.getServletContext();
//获取访问人数
Integer value=(Integer)context.getAttribute("count");
//定义访问人数变量
int count=1;
if(value==null)
{
out.write("你是第一个访问者");
}
else
{
count+=value;
}
context.setAttribute("count", count);
//统计人数
out.print(count);
//刷新流
out.flush();
//关闭流
out.close();
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }
通过此路径在浏览器*问 http://localhost:8080/webProject1/CountVisited