
ServletContext意思就是Servlet上下文对象,在一个web容器中只有一个ServletContext对象,这点有点像单例模式(也许它就是用单例模式实现的)。它凌驾于所有Servlet之上,所以可以用它来共享数据和信息,以及Servlet之间的通信。当然,由于它是全局的,所以它也可以用来获取一些全局的资源和信息,比如某个资源的绝对路径(real path)、某个资源的字节流等等。
这里主要练习用ServletContext来实现一个简单的访问量统计功能。
获取ServletContext对象- 通过HttpServletRequest对象获取
- 通过ServletConfig对象获取
- 通过继承自GenericServlet类的方法获取
public class ServletDemo09 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = req.getServletContext();
Integer count = (Integer) context.getAttribute("count");
if(count == null){
count = 1;
}else {
count++;
}
context.setAttribute("count",count);
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("n" +
"n" +
"n" +
" n" +
" 访问量 n" +
" n" +
" body{n" +
" padding: 0;n" +
" margin: 0;n" +
" height: 100vh;n" +
" line-height: 100vh;n" +
" text-align: center;n" +
" font-size: xx-large;n" +
" font-weight: 300;n" +
" }n" +
" n" +
"n" +
"n" +
" 当前页面的访问量有:"+ count +"n" +
"n" +
"");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
效果图
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)