Servlet学习笔记—ServletContext对象

来源:互联网 发布:百科题库 软件下载 编辑:程序博客网 时间:2024/06/16 03:36
  • WEB 容器在启动时,它会为每个 WEB 应用程序都创建一个对应的 ServletContext 对象,它代表当前 web 应用。
  • 由于一个 WEB 应用中的所有 Servlet 共享同一个 ServletContext 对象,因此 Servlet 对象之间可以通过 ServletContext 对象来实现通讯。 ServletContext 对象通常也被称之为 context 域对象

应用(统计站点访问次数):
web.xml文件

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">    <servlet>        <servlet-name>ServletDemo1</servlet-name>        <servlet-class>com.pl.servlet.ServletDemo1</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>ServletDemo1</servlet-name>        <url-pattern>/ServletDemo1</url-pattern>    </servlet-mapping>    <servlet>        <servlet-name>ServletDemo2</servlet-name>        <servlet-class>com.pl.servlet.ServletDemo2</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>ServletDemo2</servlet-name>        <url-pattern>/ServletDemo2</url-pattern>    </servlet-mapping>    <servlet>        <servlet-name>ServletDemo3</servlet-name>        <servlet-class>com.pl.servlet.ServletDemo3</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>ServletDemo3</servlet-name>        <url-pattern>/ServletDemo3</url-pattern>    </servlet-mapping></web-app>

建两个servlet:ServletDemo1和ServletDemo2
都为如下代码:

public class ServletDemo1 extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        ServletContext sc = getServletContext();        Integer pvcount = (Integer) sc.getAttribute("pvcount");        if(pvcount==null){            sc.setAttribute("pvcount", 1);        }else{            sc.setAttribute("pvcount", ++pvcount);        }        pvcount = (Integer) sc.getAttribute("pvcount");        String str="<font color='red' size='20'>当前站点被点击了"+pvcount+"次</font>";        resp.getOutputStream().write(str.getBytes());    }}
原创粉丝点击