Web之过滤器和监听器
1、编写java类实现Filter接口
2、重写doFilter方法
3、设置拦截的url
入门案例:
package com.qf.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* /**
* 2019/8/1216:26
*
* 未知的事情 永远充满变数
*/
*/
@WebFilter("/myservlet1")//过滤路径
public class MyFilter1 implements Filter {
//初始化过滤器
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化了........init... "+filterConfig);
}
//执行过滤
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("过滤前........doFilter ");
//放行
chain.doFilter(request, response);
System.out.println("过滤后.......doFilter");
}
//销毁
@Override
public void destroy() {
System.out.println("销毁了.....destroy");
}
}
#####1.3 过滤器的配置
在自定义的Filter类上使用注解@WebFilter(“/*”)
在web.xml中进行过滤器的配置:
sf
com.qf.web.filter.SecondFilter
sf
/*
过滤器的拦截匹配路径通常有三种形式:
(1)精确拦截地址匹配 ,比如/index.jsp
(2)后缀拦截地址匹配,比如*.jsp、*.html、*.jpg
(3)通配符匹配/*,表示匹配所有、注意过滤器不能使用/匹配。
#####1.4 过滤器链
通常客户端对服务器请求之后,服务器调用Servlet之前会执行一组过滤器(多个过滤器),那么这组过滤器就称为一条过滤器链。
每个过滤器实现某个特定的功能,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。
在一个web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。这些过滤器的执行顺序由filter-mapping的顺序决定,前面filter-mapping优先级高于后面的。
注意:
(1)如果为注解的话,是按照类名的字符串顺序进行起作用的
(2)如果web.xml,按照 filter-mapping注册顺序,从上往下
(3)web.xml配置高于注解方式
(4)如果注解和web.xml同时配置,会创建多个过滤器对象,造成过滤多次。
在过滤器的创建的时候,可以传递初始化参数
第一种:基于注解的
/**
* Servlet Filter implementation class FirstFilter 创建过滤器
*/
@WebFilter(value="/*",initParams= {@WebInitParam(name = "version", value = "1.0")})
public class FirstFilter implements Filter {
/**
* Default constructor.
*/
public FirstFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy() 销毁
*/
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy销毁……");
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) 过滤
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
System.out.println("doFilter……过滤");
// 是否继续---访问下一个
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
* 初始化
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init……初始化");
System.out.println("初始化参数:版本号:"+fConfig.getInitParameter("version"));
}
}
第二种:基于xml配置
/**
* 创建过滤器
*/
public class SecondFilter implements Filter {
/**
* Default constructor.
*/
public SecondFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy() 销毁
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) 过滤
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 是否继续---访问下一个
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
* 初始化
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("初始化参数:版本号:"+fConfig.getInitParameter("version"));
}
}
Web.xml实现配置:
Web_Day
myfilter
com.qf.web.filter.SecondFilter
version
1.0
myfilter
/*
index.html
可以实现 Web 应用程序中的预处理和后期处理逻辑
对于目前现在的浏览器,get请求动态资源缓存问题已经解决。
对于静态资源部分浏览器(IE,FixFox)使用Cache-Control头和Expires头设置缓存时间。chrome浏览器设置不设置都无效而是每次都请求服务器。
对于静态资源服务器会采用304状态码控制是否再次发送数据,从而节省带宽;可以通过Cache-Control=no-store控制304无效。
过滤器的代码:
/**
* Servlet Filter implementation class NoCacheFilter
* 实现禁止浏览器缓存动态页面
*/
@WebFilter("*.jsp")
public class NoCacheFilter implements Filter {
/**
* Default constructor.
*/
public NoCacheFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//把ServletRequest强转成HttpServletRequest
HttpServletRequest req = (HttpServletRequest) request;
//把ServletResponse强转成HttpServletResponse
HttpServletResponse resp = (HttpServletResponse) response;
//禁止浏览器缓存所有动态页面
resp.setDateHeader("Expires", -1);
resp.setHeader("Cache-Control", "no-cache"); //no-store
resp.setHeader("Pragma", "no-cache");
//放行
chain.doFilter(req, resp);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
带缓存过滤器
@WebFilter(filterName = "CacheFilter",value = "*.html")
public class CacheFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request= (HttpServletRequest) req;
HttpServletResponse response= (HttpServletResponse) resp;
response.setDateHeader("Expires",System.currentTimeMillis()+600000);//毫秒 10分钟
response.setHeader("Cache-Control", "max-age=600");//秒
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
创建数据库和用户表
DbHelper类:
package com.qf.utils;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
//数据库工具类
public class DbHelper {
private static DataSource ds;
private static QueryRunner qr;
static{
ds=new ComboPooledDataSource();
qr=new QueryRunner(ds);
}
//执行非查询语句,返回值受影响的行数
public static int execute(String sql,Object... vs){
try {
return qr.execute(sql, vs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
//执行查询语句
public static T querySingle(String sql,Class clz,Object... vs){
try {
return qr.query(sql, new BeanHandler<>(clz),vs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
User类:
public class User {
private int id;
private String username;
private String pass;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
过滤器代码:
/**
* Servlet Filter implementation class AutoLoginFilter
* 实现自动登录,只是拦截登录页面
*/
@WebFilter(value="/login.html")
public class AutoLoginFilter implements Filter {
/**
* Default constructor.
*/
public AutoLoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//强制转换为Http的请求和响应
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse rep=(HttpServletResponse) response;
//验证是否登录
if(req.getSession().getAttribute("user")==null){
//从Cookie获取上次保存的账号和密码
Cookie[] cks=req.getCookies();
User user=null;
for(Cookie c:cks){
if(c.getName().equals("user")){
String[] us=c.getValue().split("@");
user=new User();
user.setUsername(us[0]);
user.setPass(us[1]);
break;
}
}
//如果存储Cookie,那么就实现自动登录
if(user!=null){//需要自动登录
// 登录校验
User user1 = DbHelper.querySingle("select * from tb_user where username=?", User.class, user.getUsername());
boolean res=true;
if (user1 != null) {
if (user.getPass().equals(user1.getPass())) {
req.getSession().setAttribute("user", user1);
res=false;
rep.sendRedirect(req.getServletContext().getContextPath()+"/success.jsp");
}
}
if(res){//登录失败,之前的记录账号和密码错误
Cookie ck=new Cookie("user","");
ck.setPath("/");
ck.setMaxAge(0);
rep.addCookie(ck);
rep.sendRedirect(req.getServletContext().getContextPath()+"/login.jsp");
}
}
else{//直接登录页面
chain.doFilter(request, response);
}
}
else{//如果已经登录,那么就直接放行
rep.sendRedirect("success.jsp");
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
案例3 过滤脏词
public class DirtyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(new DirtyHttpServletRequest((HttpServletRequest)request), response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
static class DirtyHttpServletRequest extends HttpServletRequestWrapper{
private List dirtywords=new ArrayList();
public DirtyHttpServletRequest(HttpServletRequest request) {
super(request);
dirtywords.add("sb");
dirtywords.add("狗蛋");
dirtywords.add("扯淡");
}
@Override
public String getParameter(String name) {
// TODO Auto-generated method stub
String v=super.getParameter(name);
for (String s : dirtywords) {
v=v.replaceAll(s, "***");
}
return v;
}
}
}
案例4 过滤器解决编码
public class CharacterEncodingFilter implements Filter {
//filter配置
private FilterConfig config;
//默认编码
private String defaultcharset="utf-8";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.config=filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String charset=config.getInitParameter("charset");
if(charset==null){
charset=defaultcharset;
}
//1设置请求和响应的编码
request.setCharacterEncoding(charset);
response.setContentType("text/html;charset="+charset);
//2放行
chain.doFilter(request, response);
System.out.println("xxxxxxxxxxxxxxxx");
}
@Override
public void destroy() {
}
}
文本内容压缩就是将服务器的响应结果给压缩为gzip的格式,以便达到浏览器和服务器传输,设置消息头让浏览器自动解压。
过滤器:
/**
* Servlet Filter implementation class GlobalGzipFilter
* 实现文本内容压缩
*/
@WebFilter("*.jsp")
public class GlobalGzipFilter implements Filter {
/**
* Default constructor.
*/
public GlobalGzipFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// 重构响应对象
GzipResponse rsp=new GzipResponse((HttpServletResponse)response, new ByteArrayOutputStream());
// pass the request along the filter chain
chain.doFilter(request, rsp);
//获取响应的内容
ByteArrayOutputStream baos=rsp.getOutStream();
System.out.println("压缩之前:"+baos.size()+"字节");
//开始压缩
//创建内存流对象,存储压缩之后的的内容
ByteArrayOutputStream newbaos=new ByteArrayOutputStream();
GZIPOutputStream gzip=new GZIPOutputStream(newbaos);
gzip.write(baos.toByteArray());
gzip.flush();
gzip.close();
System.out.println("压缩之后:"+newbaos.size()+"字节");
HttpServletResponse resp=(HttpServletResponse)response;
//设置消息头,标记内容为gzip
resp.setHeader("Content-Encoding", "gzip");
resp.getOutputStream().write(newbaos.toByteArray());//写出真正的内容
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
//自定义的响应对象
private class GzipResponse extends HttpServletResponseWrapper{
private ByteArrayOutputStream baos;//内存输出字节流
private PrintWriter pw;
public GzipResponse(HttpServletResponse response,ByteArrayOutputStream baos) {
super(response);
this.baos=baos;
// TODO Auto-generated constructor stub
}
//获取响应内容的内存流对象,存储着要响应的数据
public ByteArrayOutputStream getOutStream(){
// TODO Auto-generated method stub
if(pw!=null){
pw.flush();
}
return baos;
}
@Override
public PrintWriter getWriter() throws IOException {
//将响应的内容写出到指定的内存流中
pw=new PrintWriter(new OutputStreamWriter(baos,"UTF-8"));
return pw;
}
}
}
原理:http 协议中,如果从一个网页跳到另一个网页,http 头字段里面会带个 Referer。图片服务器通过检测 Referer 是否来自规定域名,来进行防盗链。
图片防盗链有什么用?
防止其它网站盗用你的图片,浪费你宝贵的流量。
package com.qf.filter2;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* wgy 2019/4/25 9:01
*/
@WebFilter(filterName = "StealFilter",urlPatterns = {"*.jpg","*.png"})
public class StealFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request= (HttpServletRequest) req;
HttpServletResponse response= (HttpServletResponse) resp;
String referer = request.getHeader("referer");
String url="http://localhost:8080"+request.getContextPath();
System.out.println(url);
if(referer!=null&&referer.startsWith(url)){
System.out.println("页面正常请求");
chain.doFilter(req, resp);
}else{
System.out.println("盗链");
request.getRequestDispatcher("/error/steal.jpg").forward(request, response);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
1、事件监听涉及到三个组件:事件源、事件参数对象、事件监听器
2、当事件源上发生某一个动作时,它会调用事件监听器的一个方法,并在调用该方法时把事件参数对象传递进去,
开发人员在监听器中通过事件参数对象,就可以拿到事件源,从而对事件源进行操作。
案例一:GUI编程中监听机制
public static void main(String[] args) {
Frame f = new Frame();
f.setSize(400, 400);
f.setVisible(true);
f.addWindowListener(new WindowListener(){
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowClosing(WindowEvent e) {
Frame f = (Frame) e.getSource();
f.dispose();
}
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
});
}
案例二:观察者设计模式的实现
//设计一个事件源,被监听器监听 Observer(观察者设计模式)
public class Demo2 {
/**
* @param args
*/
public static void main(String[] args) {
Person p = new Person();
p.registerListener(new PersonListener(){
public void doeat(Event e) {
Person p = (Person)e.getSource();
System.out.println(p.getName() + "吃啥呢");
}
public void dorun(Event e) {
Person p = (Person)e.getSource();
System.out.println(p.getName() + "减肥呢");
}
});
p.eat();
}
}
class Person{
private String name;
private PersonListener listener;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public void eat(){
System.out.println(name+"要吃东西了...");
if(listener!=null){
listener.doeat(new Event(this));
}
}
public void run(){
System.out.println(name+"要跑步了...");
if(listener!=null){
listener.dorun(new Event(this));
}
}
public void registerListener(PersonListener listener){
this.listener = listener;
}
}
interface PersonListener{
public void doeat(Event e);
public void dorun(Event e);
}
class Event{
private Object source;
public Event() {
super();
// TODO Auto-generated constructor stub
}
public Event(Person source) {
super();
this.source = source;
}
public Object getSource() {
return source;
}
public void setSource(Object source) {
this.source = source;
}
}
监听器用于监听web应用中某些对象(request,session,application)、信息的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计访问人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等等。
2.2.1 生命周期监听器:
1 ServletContext上下文监听器
ServletContextListener接口
内部方法:
初始化:contextInitialized
销毁:contextDestroyed
2 Session监听器
HttpSessionListener
内部方法:
sessionCreated:监听Session对象的创建
sessionDestroyed:监听Session对象的销毁
3 request监听器
ServletRequestListener
监听request对象的初始化和销毁
内部方法:
1、requestInitialized:监听request对象的初始化
2、requestDestroyed:监听request对象的销毁
2.2.2属性变化监听器:
1 ServletContext属性变化监听器
ServletContextAttributeListener接口
内部的方法:
attributeAdded:监听属性的添加
attributeRemoved:监听属性的移除
attributeReplaced:监听属性的修改
2 session属性变化监听器
HttpSessionAttributeListener
监听HttpSession的内容的变化
内部的方法:
attributeAdded:监听属性的添加
attributeRemoved:监听属性的移除
attributeReplaced:监听属性的修改
3 request属性变化监听器
ServletRequestAttributeListener
监听属性内容变化
内部方法:
attributeAdded:监听属性的添加
attributeRemoved:监听属性的移除
attributeReplaced:监听属性的修改
2.2.3感知型监听器:
1 对象从session添加或移除
HttpSessionBindingListener
监听对象的添加和移除
内部方法:
valueBound:监听对象的绑定
valueUnbound:监听对象的解除绑定
2 对象钝化和活化
HttpSessionActivationListener
监听session的钝化和活化
内部方法:
sessionWillPassivate:监听Session内部存储对象的钝化-写入
sessionDidActivate:监听Session内部存储对象的活化-读取
对应类需要实现序列化接口Serializable
在 web目录下创建META-INF文件夹,在META-INF文件夹中创建context.xml文件
在web.xml中进行配置
com.qf.web.listener.RequestLeftListener
Servlet3.0之后新增的,使用注解@WebListener进行监听器的注册
a. 实现ServletContext生命周期的监听
/**
* Application Lifecycle Listener implementation class FirstListener
*监听ServletContext的初始化和销毁
*/
@WebListener//注解式注册
public class ApplicationListener implements ServletContextListener {
/**
* Default constructor.
*/
public ApplicationLeftListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
* 销毁
*/
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("网站被销毁了"+sce.getServletContext().hashCode());
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
* 初始化
*/
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("网站初始化完成"+sce.getServletContext().hashCode());
sce.getServletContext().setAttribute("fwrs", 0);
}
}
b. ServletContext属性内容的变化
/**
* Application Lifecycle Listener implementation class ApplicationAttributeListener
* 实现ServletContext属性内容变化
*/
@WebListener
public class ApplicationAttributeListener implements ServletContextAttributeListener {
/**
* Default constructor.
*/
public ApplicationAttributeListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
* 新增内容
*/
public void attributeAdded(ServletContextAttributeEvent event) {
// TODO Auto-generated method stub
System.out.println("attributeAdded:"+event.getName());
}
/**
* @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
* 删除属性内容
*/
public void attributeRemoved(ServletContextAttributeEvent event) {
// TODO Auto-generated method stub
System.out.println("attributeRemoved:"+event.getName());
}
/**
* @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
* 修改内容
*/
public void attributeReplaced(ServletContextAttributeEvent event) {
// TODO Auto-generated method stub
System.out.println("attributeReplaced:"+event.getName());
}
}
a. 实现HttpSession生命周期的变化和属性内容的变化和id变化
/**
* Application Lifecycle Listener implementation class SessionLeftListener
* 该监听器实现HttpSession的生命周期变化和属性内容的变化
*
*/
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener{
/**
* Default constructor.
*/
public SessionLeftListener() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpSessionListener#sessionCreated(HttpSessionEvent)
* Session的创建
*/
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
System.out.println("sessionCreated");
int ct=(int) se.getSession().getServletContext().getAttribute("fwrs");
se.getSession().getServletContext().setAttribute("fwrs", ++ct);
se.getSession().setAttribute("tea", new Teacher("西施"));
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
* Session的销毁
*/
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
System.out.println("sessionDestroyed");
}
/**
* @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
* Session中属性内容的添加
*/
public void attributeAdded(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
* Session中属性内容的移除
*/
public void attributeRemoved(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
* Session中属性内容的修改
*/
public void attributeReplaced(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
//监听HttpSession的id的变化,Servlet3.1新特性
@Override
public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
// TODO Auto-generated method stub
}
}
案例:实现访问人数统计
public class VisitCountListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
//负责人数增加
ServletContext application=se.getSession().getServletContext();
Integer count=(Integer)application.getAttribute("count");
if(count==null){
application.setAttribute("count", 1);
}else{
application.setAttribute("count", count+1);
}
System.out.println("人数增加了");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
//负责人数的减少
ServletContext application=se.getSession().getServletContext();
Integer count=(Integer)application.getAttribute("count");
application.setAttribute("count", count-1);
System.out.println("人数减少了");
}
}
a. 监听ServletRequest生命周期和属性内容变化
/**
* Application Lifecycle Listener implementation class RequestLeftListener
*监听Request对象的内容
*/
//@WebListener
public class RequestListener implements ServletRequestAttributeListener,ServletRequestListener {
/**
* Default constructor.
*/
public RequestLeftListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletRequestListener#requestInitialized(ServletRequestEvent)
* 请求对象的初始化
*/
public void requestInitialized(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
* 销毁
*/
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)
* 移除属性内容
*/
public void attributeRemoved(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent)
* 添加
*/
public void attributeAdded(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)
* 修改
*/
public void attributeReplaced(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
}
自定义Session管理器,session会话,会话的默认有效30分钟, 需要使用开发人员自己管理session的有效期,不需要系统管理。
功能1:把所有的session放入集合中。
功能2:遍历集合中每个session, 判断session有多长时间没有访问了,如果超过1分钟,把session失效了。###### 案例:Session管理器
package com.qf.listener;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.enterprise.inject.New;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionManagerListener implements HttpSessionListener,ServletContextListener {
private static Object lock=new Object();
private Timer timer;
//保存所有的session
private List sessions=new LinkedList();
@Override
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
synchronized (lock) {
sessions.add(se.getSession());
}
System.out.println("添加了session....."+se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
System.out.println("销毁了session...."+se.getSession().getId());
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
//启动定时器
timer=new Timer();
timer.schedule(new MyTimerTask(), 0, 60*1000);
System.out.println("定时器启动");
//把集合放入application中
sce.getServletContext().setAttribute("sessions", sessions);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
timer.cancel();//取消定时器
System.out.println("定时器取消了...");
}
class MyTimerTask extends TimerTask{
@Override
public void run() {
Iterator it=sessions.iterator();
synchronized (lock) {
while(it.hasNext()){
HttpSession session=it.next();
if(System.currentTimeMillis()-session.getLastAccessedTime()>60000){
session.invalidate();//session失效
it.remove();
}
}
}
}
}
}