如何在Java servlet上下文中获取和设置全局对象 [英] How to get and set a global object in Java servlet context

查看:56
本文介绍了如何在Java servlet上下文中获取和设置全局对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人可以提供建议:我有一个场景,Quartz运行的预定作业每小时都会更新一个对象的arraylist。

I wonder if anyone can advise: I have a scenario where a scheduled job being run by Quartz will update an arraylist of objects every hour.

但我需要这些对象的arraylist对Tomcat创建的所有会话都是可见的。所以我想的是我每隔一小时就从运行的Quartz作业中的某个地方写这个对象,这样每个会话都可以访问它。

But I need this arraylist of objects to be visible to all sessions created by Tomcat. So what I'm thinking is that I write this object somewhere every hour from the Quartz job that runs so that each session can access it.

任何人都可以说这是多么好可能会实现?我想知道从Quartz作业写入servlet上下文的对象?另一种方法是让每个会话从数据库表中填充对象的arraylist。

Can anyone say how best this may be achieved? I was wondering about the object being written to servlet context from the Quartz job? The alternative is having each session populate the arraylist of objects from a database table.

谢谢

摩根先生。

推荐答案

是的,我会将列表存储在 ServletContext 中应用程序范围的属性。从数据库中提取数据可能效率较低,因为您每小时只更新一次列表。为了给Quartz任务提供对 ServletContext 对象的引用,可能需要创建 ServletContextListener ServletContext 只能从与Servlet和Listeners等JavaEE相关的类中检索。

Yes, I would store the list in the ServletContext as an application-scoped attribute. Pulling the data from a database instead is probably less efficient, since you're only updating the list every hour. Creating a ServletContextListener might be necessary in order to give the Quartz task a reference to the ServletContext object. The ServletContext can only be retrieved from JavaEE-related classes like Servlets and Listeners.

编辑:
在ServletContextListener中,当您创建作业时,可以通过将列表添加到JobDataMap将列表传递到作业中。

In the ServletContextListener, when you create the job, you can pass the list into the job by adding it to a JobDataMap.

public class MyServletContextListener implements ServletContextListener{
  public void contextInitialized(ServletContextEvent event){
    ArrayList list = new ArrayList();

    //add to ServletContext
    event.getServletContext().setAttribute("list", list);

    JobDataMap map = new JobDataMap();
    map.put("list", list);
    JobDetail job = new JobDetail(..., MyJob.class);
    job.setJobDataMap(map);
    //execute job
  }

  public void contextDestroyed(ServletContextEvent event){}
}

//Quartz job
public class MyJob implements Job{
  public void execute(JobExecutionContext context){
    ArrayList list = (ArrayList)context.getMergedJobDataMap().get("list");
    //...
  }
}

这篇关于如何在Java servlet上下文中获取和设置全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆