1.简介
服务器会在项目启动时创建一个ServletContext对象,在服务器关闭时销毁该对象,它的作用是在整个应用之间共享数据。
2.获取ServletContext对象
- ServletConfig的getServletContext()
- GerericServlet的getServletContext()
- HttpSession的getServletContext()
- ServletContextEvent的getServletContext()
3.域对象(在Servlet中存取数据)
- setAttribute()
- getAttribute()
- removeAttribute()
- getAttributeNames()
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.getServletContext().setAttribute("name","steven");
}
}
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(this.getServletContext().getAttribute("name"));
}
}
<servlet>
<servlet-name>AServlet</servlet-name>
<servlet-class>AServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>BServlet</servlet-name>
<servlet-class>BServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AServlet</servlet-name>
<url-pattern>/A</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>BServlet</servlet-name>
<url-pattern>/B</url-pattern>
</servlet-mapping>
4.获取公共的初始化参数(所有Servlet都可以使用)
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
System.out.println(servletContext.getInitParameter("a"));
}
}
<context-param>
<param-name>a</param-name>
<param-value>aaa</param-value>
</context-param>
<servlet>
<servlet-name>AServlet</servlet-name>
<servlet-class>AServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AServlet</servlet-name>
<url-pattern>/A</url-pattern>
</servlet-mapping>
5.获取资源相关方法
- 资源路径:getRealPath()
- 资源流:getResourceAsStream()
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String path = servletContext.getRealPath("index.jsp");
System.out.println(path);
InputStream inputStream = new FileInputStream(path);
}
6.统计页面访问量
ServletContext servletContext = this.getServletContext();
Integer count = (Integer) servletContext.getAttribute("count");
if(count == null){
servletContext.setAttribute("count",1);
}else{
servletContext.setAttribute("count",++count);
}
System.out.println(servletContext.getAttribute("count"));