35、servlet--servletContext

servletContext接口是Servlet中最大的一个接口;
WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
session对应的是浏览器,而servletContext是对应的web容器,供多个浏览器共享;

应用场景:
1、记录在线人数
2、你是第多少位访问者
3、公共聊天室
4、获取项目全路径/读取资源文件 
String realPath = this.getServletContext().getRealPath("/images/1.jpg");
提供不同用户共享,数据量不大,不写入数据库 时可用servletContext对象;


通过ServletConfig.getServletContext获取,类似session也是单例的;
创建:
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			ServletContext sc = this.getServletContext();
			sc.setAttribute("name", "nick");
			System.out.println(System.currentTimeMillis());
			request.getRequestDispatcher("/pages/sc.jsp").forward(request, response);
    		return; 
	}

获取:
<% ServletContext sc = this.getServletContext();
   String name = (String)sc.getAttribute("name");
%>
<%=name %>

  <a href="<%=path%>/servlet/ServletCo"> ServletContext </a><br>
    <a href="<%=path%>/pages/sc.jsp"> ServletContext.jsp </a><br>
先重启tomcat,先执行ServletContext ,后无论那台执行ServletContext.jsp,都得到nick;

删除属性:
sc.removeAttribute("name");

网页计数器:
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		    //登陆一次算一次访问
		    //http://www.nick.org:8182/login/servlet/ServletCo?id=111
		    String id = request.getParameter("id");
		    ServletContext sc = this.getServletContext();
		    if(null !=id && id.equals("111"))
		    {
		    	Integer count = (Integer)sc.getAttribute("count");
		    	if(count == null)
		    	{
		    		count =1;
		    	}else
		    	{
		    		count++;
		    	}
		    	sc.setAttribute("count", count);
		    }
			//防止刷新!用responset跳走
		    //request.getRequestDispatcher("/pages/sc.jsp").forward(request, response);
    		response.sendRedirect(request.getContextPath()+"/pages/sc.jsp");
		    return; 
	}



在tomcat停止或重启时 将上次访问量存入数据库:
方案:启用init()和destroy()方法:
 <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>MyInitServlet</servlet-name>
    <servlet-class>org.nick.server.MyInitServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>


public void destroy() {
		super.destroy(); 
		Integer count = 0;
		//关闭web容器时ServletContext中的计数
		count = (Integer)this.getServletContext().getAttribute("count");
		String sql = "insert into ser_count (time,count) value (?,?)";
		Object[]   parameters = {new java.util.Date(),count};
		DBUtil.executeUpdate(sql, parameters);
		System.out.println("here done");
	}


同理init,从数据库中读取上次的访问量;


隔断时间存入数据库(一小时/次):Timer,在init()方法中每3600s写入一次;
public void init() throws ServletException {
		Timer   timer   =   new   Timer();     
        timer.schedule(new   MyTask(),   0,   1000*2);     
	}

public class MyTask extends TimerTask {
	@Override
	public void run() {
		System.out.println("okk");
	}
}



项目下载地址:

你可能感兴趣的:(servletContext)