GVKun编程网logo

如何使用Spring将依赖项注入HttpSessionListener?(spring如何实现依赖注入)

18

最近很多小伙伴都在问如何使用Spring将依赖项注入HttpSessionListener?和spring如何实现依赖注入这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展HttpS

最近很多小伙伴都在问如何使用Spring将依赖项注入HttpSessionListener?spring如何实现依赖注入这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展HttpSessionListener和HttpSessionAttributeListener区别、servletContextListener、httpSessionListener和servletRequestListener使用整理、asp.net-mvc – 如何使用Windsor将依赖项注入到ActionFilterAttributes中、HttpSessionBindingListener等相关知识,下面开始了哦!

本文目录一览:

如何使用Spring将依赖项注入HttpSessionListener?(spring如何实现依赖注入)

如何使用Spring将依赖项注入HttpSessionListener?(spring如何实现依赖注入)

如何在不使用调用的情况下使用Spring将依赖项注入HttpSessionListener中context.getBean("foo-bar")

答案1

小编典典

由于Servlet 3.0 ServletContext具有“ addListener”方法,因此可以通过如下代码添加而不是在web.xml文件中添加侦听器:

@Componentpublic class MyHttpSessionListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        if (applicationContext instanceof WebApplicationContext) {            ((WebApplicationContext) applicationContext).getServletContext().addListener(this);        } else {            //Either throw an exception or fail gracefully, up to you            throw new RuntimeException("Must be inside a web application context");        }    }           }

这意味着你可以正常地注入“ MyHttpSessionListener”中,并且,只要你的应用程序上下文中存在bean,就会使侦听器注册到容器中

<Listener>HttpSessionListener和HttpSessionAttributeListener区别

HttpSessionListener和HttpSessionAttributeListener区别

一、HttpSessionListener

       HttpSessionListener是对Session的一个监听,主要监听关于Session的两个事件,即初始化和销毁。HttpSessionListener有两个方法:


VoidsessionCreated(HttpSessionEvent se):当session创建时会收到通知。


VoidsessionDestroyed(HttpSessionEvent se):当session销毁时也会收到通知。

在调用session.invalidate()方法时,就会调用VoidsessionDestroyed()销毁方法。
       故根据HttpSessionListener的特性,如果想在用户登录或者退出时做些什么,就可以设置session监听,例如:防止用户重复登录,统计用户在线数量,统计用户登录频率等等。

二、HttpSessionAttributeListener

       HttpSessionAttributeListener是SessionAttribute的监听,当在会话对象中加入属性、移除属性或替换属性时,就会调用HttpSessionAttributeListener监听器。

       它有三个方法:


 public voidattributeAdded(HttpSessionBindingEvent se):在session中添加对象时触发此操作

 public voidattributeRemoved(HttpSessionBindingEvent se):修改、删除session中添加对象时触发此操作

 public voidattributeReplaced(HttpSessionBindingEvent se):在Session属性被重新设置时

 

三、来个例子

1、web.xml配置

 

2、监听实现类

 

<Listener>servletContextListener、httpSessionListener和servletRequestListener使用整理

servletContextListener、httpSessionListener和servletRequestListener使用整理

在java web应用中,listener监听器似乎是不可缺少的。经常常使用来监听servletContext、httpSession、servletRequest等域对象的创建、销毁以及属性的变化等等,能够在这些事件动作前后进行一定的逻辑处理。


比較经常使用的应用场景是利用监听器来初始化一些数据、统计在线人数、统计web应用浏览量等等。


这里所说的监听器实际上是servlet规范中定义的一种特殊类,须要实现特定的接口。 
而我临时先说当中三个用来监听域对象的,各自是servletContextListener、httpSessionListener、servletRequestListener。 
这三个接口写法上实际是几乎相同的。都有两个分别代表了该域对象创建时调用和销毁时调用的方法。据我的理解,这三个对象最大的差别应该就是作用域不一样。


servletContext在整个应用启动到结束中生效。启动系统时创建这个对象,整个过程中这个对象是唯一的。 
httpSession则是在一个session会话中生效,在一个session被创建直到失效的过程中都起作用,只是一个启动的应用中httpSession对象能够有多个,比方同一台电脑两个浏览器訪问。就会创建两个httpSession对象。 
而servletRequest是在一个request请求被创建和销毁的过程中生效,每发起一次请求就会创建一个新的servletRequest对象,比方刷新浏览器页面、点击应用的内链等等。 
这三个监听器的写法基本例如以下伪代码所看到的: 
首先创建一个监听器类实现对应的接口及方法:

package packageName;
public class ListenerName implements *Listener {

    @Override
    public void 对象创建时被调用的方法(对应的事件 arg0) {

    }

    @Override
    public void 对象销毁时被调用的方法(对应的事件 arg0) {

    }
}

 

然后在web.xml中注冊:

<listener>
    <listener-class>packageName.ListenerName</listener-class>
  </listener>

 

到这里,基本上这个监听器在启动web服务器以后就能够正常跑了,仅仅是有时候我们还会在注冊监听器的时候配置一些其它的。 
比方配置servletContextListener的时候,可能会加上context-param參数:

<context-param>
     <param-name>paramName</param-name>
     <param-value>paramValue</param-value>
</context-param>

 

配置httpSessionListener的时候,可能会加上session超时:

<session-config>
     <session-timeout>1</session-timeout>
</session-config>

 

我感觉经过这样一整理后,就会发现起始监听器写起来还是非常easy的。于是便模拟简单的实现了在线用户统计和应用訪问量,基本代码例如以下: 
首先是实现了servletContext

package webTest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ListenerTest1 implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("contextDestroyed" + "," + new Date());
        Object count = arg0.getServletContext().getAttribute("count");
        File file = new File("count.txt");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(count.toString());
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("contextInitialized" + "," + new Date());
        File file = new File("count.txt");
        if (file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
                BufferedReader bReader = new BufferedReader(inputStreamReader);
                String count = bReader.readLine();
                System.out.println("历史訪问次数:" + count);
                arg0.getServletContext().setAttribute("count", count);
                bReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

这里我把訪问次数存在一个txt文件里。以便于持久化保存。当项目启动的时候。也就是创建servletContext对象的时候调用载入方法。从txt文件里读取历史訪问量,然后使用setAttribute方法把这个数据存入到内存中。 
之后当应用被关闭,servletContext对象被销毁的时候把内存中新的訪问量数据覆盖写入到txt文件。以便于下次启动应用后继续读取之前的訪问量。 
然后使用servletRequestListener来实现web浏览量的变化,当然了。这里仅仅是简单的实现,假设是要实现那种同一个用户刷新页面不添加浏览量的功能,还须要做很多其它的处理。

package webTest;
import java.util.Date;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class ListenerTest3 implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent arg0) {
        System.out.println("requestDestroyed" + "," + new Date());
        System.out.println("当前訪问次数:" + arg0.getServletContext().getAttribute("count"));
    }

    @Override
    public void requestInitialized(ServletRequestEvent arg0) {
        System.out.println("requestInitialized" + "," + new Date());
        Object count = arg0.getServletContext().getAttribute("count");
        Integer cInteger = 0;
        if (count != null) {
            cInteger = Integer.valueOf(count.toString());
        }
        System.out.println("历史訪问次数::" + count);
        cInteger++;
        arg0.getServletContext().setAttribute("count", cInteger);
    }

}

 

这里相同是两个方法,在servletRequest对象被建立的时候调用初始化方法。从内存中读取servletContext对象的count属性,而后输出历史訪问量。


同一时候在此基础上加一又一次设置servletContext对象的count属性的内容。当servletRequest对象被销毁的时候调用销毁时的方法打印出当前浏览量。这样就简单的实现了web浏览的量的累加计数。 
然后就是利用httpSessionListener来实如今线人数的统计:

package webTest;
import java.util.Date;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class ListenerTest2 implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent arg0) {
        System.out.println("sessionCreated" + "," + new Date());
        Object lineCount = arg0.getSession().getServletContext().getAttribute("lineCount");
        Integer count = 0;
        if (lineCount == null) {
            lineCount = "0";
        }
        count = Integer.valueOf(lineCount.toString());
        count++;
        System.out.println("新上线一人,历史在线人数:" + lineCount + "个,当前在线人数有: " + count + " 个");
        arg0.getSession().getServletContext().setAttribute("lineCount", count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        System.out.println("sessionDestroyed" + "," + new Date());
        Object lineCount = arg0.getSession().getServletContext().getAttribute("lineCount");
        Integer count = Integer.valueOf(lineCount.toString());
        count--;
        System.out.println("一人下线,历史在线人数:" + lineCount + "个。当前在线人数: " + count + " 个");
        arg0.getSession().getServletContext().setAttribute("lineCount", count);
    }

}

 

这里的代码都非常easy。太多必要解释,须要说明的是。这里把lineCount存放在servletContext对象中并非唯一的方式,有兴趣的朋友能够尝试其它的方式。比如使用类属性。

asp.net-mvc – 如何使用Windsor将依赖项注入到ActionFilterAttributes中

asp.net-mvc – 如何使用Windsor将依赖项注入到ActionFilterAttributes中

看过如何 NInject can do it和 AutoFac can do it我试图找出如何注入依赖项到MVC ActionFilters使用城堡温莎

目前,我正在使用一个丑陋的静态IoC帮助器类来解析构造函数代码的依赖关系,如下所示:

public class MyFilterattribute : ActionFilterattribute
{    
  private readonly IUserRepository _userRepository;
  public MyFilterattribute() : this(IoC.Resolve<IUserRepository>()) { }
  public MyFilterattribute(IUserRepository userRepository)
  {
     _userRepository = userRepository;
  }
}

我想从我的过滤器中删除静态反模式IoC的东西。

有什么提示,我将如何去与温莎城堡一起去做?

不,改变DI框架不是一个选择。

解决方法

创建一个通用属性:MyFilterattribute,其中ctor采用Type作为参数 – 即这样:
public class MyFilterattribute : ActionFilterattribute {
    public MyFilterattribute(Type serviceType) {
        this.serviceType = serviceType;
    }

    public override void OnActionExecuting(FilterExecutingContext c) {
        Container.Resolve<IFilterService>(serviceType).OnActionExecuting(c);
        // alternatively swap c with some context defined by you
    }

    // (...) action executed implemented analogously

    public Type ServiceType { get { return serviceType; } }
    public IWindsorContainer Container { set; get; }
}

然后使用与您所指的两个文章相同的方法,以便控制如何调用操作,并将WindsorContainer手动注入该属性。

用法:
[MyFilter(typeof运算(IMyFilterService))]

您的实际过滤器将在一个实现IMyFilterService的类中,而后者又应该实现IFilterService,可以看起来像这样:

public interface IFilterService {
    void ActionExecuting(ActionExecutingContext c);
    void ActionExecuted(ActionExecutedContext c);
}

这样你的过滤器甚至不会被绑定到ASP.NET MVC,你的属性只是一个元数据 – 它实际上应该是这样的!

总结

以上是小编为你收集整理的asp.net-mvc – 如何使用Windsor将依赖项注入到ActionFilterAttributes中全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

HttpSessionBindingListener

HttpSessionBindingListener

HttpSessionBindingListener

    1.BindingListener有2个方法,valueBound(HttpSessinBindingEvent)和valueUnbount(HttpSessionBindingEvent)。实现BindingListener接口的对象被绑 定到session时触发valueBound事件,解除绑定时触发valueUnbound事件。举例来说:

[c-sharp] view plain copy
  1. public class UserObject implements HttpSessionBindingListener{      
  2.         public void valueBound(HttpSessionBindingEvent event){          
  3.             System.out.println("触发绑定事件!");      
  4.             }      
  5.         public void valueUnbound(HttpSessionBindingEvent event){          
  6.             System.out.println("解除和session的绑定");      
  7.               
  8.         }  

 

UserObject user = new UserObject();

触发valueBound事件有:

1.当把该监听器保存到session中,session.setAttribute("user",user)

触发valueUnbound事件有:

1.执行session.setAttribute("onlineUserListener", "其他对象");或session.removeAttribute("onlineUserListener");将listener从session中删除时。

注意:只有当该监听器(UserObject)保存到session中或从session移除时才会触发事件,其他没有实现该listener对象保存到session时不会触发该事件。

    2.AttributeListener接口有3个方法,attributeAdded(HttpSessionBindingEvent),attributeRemoved(HttpSessionBindingEvent),

attributeReplaced(HttpSeesionEvent)。当在session中添加、移除或更改属性值时会触发相应的事件。

总结:

1.只有实现了HttpSessionBindingListener的类,在和session绑定、解除绑定时触发其事件。

2.要获取添加在session的值,用事件源的session去获取,而不要用事件源的getValue(), 会获取null。

3.HttpSessionBindingListener中如果session覆盖属性,不会触发valueBound方法。

4.若要获取销毁的session的属性应在HttpSessionListener接口中的sessionDestroyed方法中实现。

今天关于如何使用Spring将依赖项注入HttpSessionListener?spring如何实现依赖注入的介绍到此结束,谢谢您的阅读,有关HttpSessionListener和HttpSessionAttributeListener区别、servletContextListener、httpSessionListener和servletRequestListener使用整理、asp.net-mvc – 如何使用Windsor将依赖项注入到ActionFilterAttributes中、HttpSessionBindingListener等更多相关知识的信息可以在本站进行查询。

本文标签: