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

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

问题描述

我想知道是否有人可以提供建议:我有一个场景,Quartz 运行的计划作业每小时更新一个对象数组列表.

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.

但我需要这个对象数组列表对 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 上下文的对象?另一种方法是让每个会话从数据库表中填充对象数组.

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 只能从 JavaEE 相关的类(如 Servlets 和 Listeners)中检索.

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天全站免登陆