首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Servlet器皿与Web应用

2013-04-09 
Servlet容器与Web应用当Servlet容器启动时,会启动所有的Web应用。通过控制台启动Web应用。Servlet容器启动We

Servlet容器与Web应用

当Servlet容器启动时,会启动所有的Web应用。
通过控制台启动Web应用。

Servlet容器启动Web应用时,并为每个Web应用创建惟一的ServletContext对象。可以把ServletContext看成是一个Web应用的服务器组件的共享内存。

CountServlet.java
import java.io.IOException;

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 CountServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
{
    //得到一个ServletContext对象
    ServletContext context=req.getSession().getServletContext();
    //判断context容器中没有元素
    if(null==context.getAttribute("counter"))
    {
        context.setAttribute("counter",1);    
    }
    //如果context容器中有元素
    else
    {
        int counter=(Integer)context.getAttribute("counter");
        context.setAttribute("counter",counter+1);
        
    }
    //实现请求转发。
    req.getRequestDispatcher("counter.jsp").forward(req,resp);
}
}

counter.jsp

 <body>
    计数器:<%= application.getAttribute("counter") %>
  </body>

热点排行