1.监听器---->Context,Session
what is listener?
监听器是一个接口内容由我们实现,会在特定时间被调用,监听器用于监听web应用中三大域对象(request,session,application),信息的创建,销毁,增加,修改,删除等动作的发生,然后做出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等。
ContextListener通过实现ServletContextListener来进行全局监听 ContextListener可以通过记录用户访问网站的次数 思路:用户通过访问index.jsp,来获取存放在监听器中的hashmap< String,Integer>,然后在index.jsp中进行判断。 ContextListener的代码思路如下:
public class ContextListener1 implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("init");
Map<String, Integer> map = new HashMap<String, Integer>();
ServletContext context = servletContextEvent.getServletContext();
context.setAttribute("map", map);
System.out.println(map.isEmpty());
System.out.println(map);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("destory");
}
}
index.jsp的代码思路如下:
<%
String ServerName = request.getServerName();
Map<String, Integer> map = (Map<String, Integer>) application.getAttribute("map");
if (map.containsKey(ServerName)) {
map.put(ServerName, map.get(ServerName) + 1);
} else {
map.put(ServerName, 1);
}
int count = map.get(ServerName);
int size = map.size();
%>
<h4>ip地址是:<%=ServerName%>,您是第<%=count%>位访问的用户,当前服务器共被<%=size%>个用户访问过</h4>
2.监听器三大作用域
3.属性监听器
属性监听器主要监听属性值的变化,例如request.setAttribute()等这些数据的变化。
package listener;
import javax.servlet.*;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class AttrListener implements ServletContextAttributeListener, ServletRequestAttributeListener, HttpSessionAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
}
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
}
@Override
public void attributeAdded(ServletRequestAttributeEvent servletRequestAttributeEvent) {
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent servletRequestAttributeEvent) {
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent servletRequestAttributeEvent) {
}
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
}
}
4.过滤器
4.1过滤器的使用
1.编写java 类实现Filter接口
2.重写doFilter()方法
3.设置拦截的url
4.2过滤器的拦截路径
/*:根目录下所有请求都拦截 /*.do:所有带.do的请求都拦截 /*.jsp
4.3过滤器的拦截顺序
过滤器的拦截顺序,取决于在配置文件web.xml的先后顺序
4.4过滤器的四种拦截方式
|