写在之前:
再次理了理利用session的页面跳转,首先是html文件的action=”login”和对应的Servlet在web.xml里的映射路径一致——/login,如果利用MVC的内容,则action=”login.jsp”,则跳转到该jsp文件进行相应的操作。这时到LoginServlet之后,会再次进行验证,进行页面跳转。
也就是以下的语句:
request.getRequestDispatcher(“listHero”).forward(request,response);
服务端跳转,值得注意的是——request.getRequestDispatcher()
里的路径最好写web.xml文件里的路径,不然部分内容不会显示。
再如response.sendRedirect(); 客户端跳转可以直接写文件的文件名
listener正文:
Listener 的作用是用于监听 web应用的创建和销毁,以及在其上attribute发生的变化。
web应用即ServletContext对象(jsp的隐式对象application)
除了对web应用的监听外,还能监听session和request的生命周期,以及他们的attribute发生的变化。
对Context的监听分生命周期的监听,和Context上Attribute变化的监听两种
ContextListener 实现接口ServletContextListener
有两个方法
public void contextDestroyed(ServletContextEvent arg0)
对应当前web应用的销毁
public void contextInitialized(ServletContextEvent arg0)
对应当前web应用的初始化
相应的xml文件:
<listener>
<listener-class>listener.ContextListener</listener-class>
</listener>
启动时的tomcat后台的会观察到:
web应用的自动重载需要如下前提:
- 配置: server.xml中对应的<context配置 的属性 @reloadable=“true”
- 某个servlet 发生了变化,导致这个web应用自动重启
编写 ContextAttributeListener
ContextAttributeListener 实现接口ServletContextAttributeListener,
分别提供如下方法:
public void attributeAdded(ServletContextAttributeEvent e)
监听属性的增加
public void attributeRemoved(ServletContextAttributeEvent e)
监听属性的移除
public void attributeReplaced(ServletContextAttributeEvent e)
监听属性的替换
<listener>
<listener-class>listener.ContextAttributeListener</listener-class>
</listener>
利用 jsp文件故意造成context的属性增加和删除:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
application.setAttribute("test", 1);
application.setAttribute("test", 2);
application.removeAttribute("test");
%>
context的补充:
对web应用context的监听其实是对全局参数的监听,也就是servletcontext
servletContext和application 是一样的,就相当于一个类创建了两个不同名称的变量
在servlet中ServletContext就是application对象,而在JSP中application是servletcontext的对象
如:ServletContext application = e.getSession().getServletContext();
两者的区别就是:application用在jsp中,servletContext用在servlet中