版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons)
public class Aservlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取ServletContext对象
//从对象中获取名为count的属性
//如果存在,给访问量+1,然后再保存回去
//如果不存在,说明时第一次访问,向ServletContext中保存count的属性,值为1
ServletContext app=this.getServletContext();
Integer count=(Integer) app.getAttribute("count");
if(count==null){
app.setAttribute("count", 1);
}else{
app.setAttribute("count", count+1);
}
/**
* 向浏览器输出,需要使用响应对象
*/
PrintWriter pw=response.getWriter();
pw.print(count);
}
}
然后在浏览器访问该servlet,每访问一次会加一。