一、什么是servletContext:
servletContext可以理解為服務器端的一個共享空間,它可以被所有的客戶端訪問。基于這種特性,我們就可以利用servletContext做計數器等應用。
我們用個圖來描述cookie、session、servletContext的區別
//ShowTimesServlet.java /*Servlet實現訪問次數的例子!*/
import java.io.*;
import java.util.zip.*;
import javax.servlet.*;
import javax.servlet.http.*;
/*
這個類實現訪問次數。顯示訪問次數!看是第幾次訪問!
*/
public class ShowTimesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
response.setContentType( " text/html" );
HttpSession session = request.getSession();
String heading;
Integer accessCount =(Integer)session.getAttribute( " accessCount" );
if (accessCount == null ) {
accessCount = new Integer( 0 );
heading = " Welcom,You are first time to visit!" ;
}
else {
heading = " Welcome Backer" ;
accessCount = new Integer(accessCount.intValue()+ 1 );
}
session.setAttribute( " accessCount" ,accessCount);
PrintWriter out = response.getWriter();
out.println( " The title:" +heading);
out.println( " Access count: " +accessCount);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
doGet(request,response);
}
}
下面是通過servleContext來做訪問次數
Java代碼
package org.linweihan.test;
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 TestServletContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this .getServletContext();
Integer accessCount =(Integer)servletContext.getAttribute( " accessCount" );
if (accessCount == null ){
accessCount = 0 ;
} else {
accessCount = accessCount + 1 ;
}
servletContext.setAttribute( " accessCount" , accessCount);
PrintWriter out = response.getWriter();
out.println( " < html> < body> < h2> " +accessCount+ " < /body> < /html> " );
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
區別
在于session是局部的,servletContext是共享的.
當換了另一個窗口開始訪問又從0開始計數,而servletContext則是接下去計數.
二、怎樣使用ServletContext
1、首先得到ServletContext
this.getServletContext();
2、ServletContext也是和session一樣像一張表,分為屬性、值
添加屬性:setAttribute(String name,Object obj);
得到值:getAttribute(String name);
刪除屬性:removeAttribute(String name);
3、生命周期
ServletContext中的屬性的生命周期從創建開始,到服務器關閉而結束
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
