Java 如何从打开文件的不同JSP页面关闭文件

Java 如何从打开文件的不同JSP页面关闭文件,java,file,jsp,Java,File,Jsp,我有一个JSP页面,其中一类用户users\u group\u 1需要处理一个文件所有这些方法都使用同一个文件,因此,由于我使用JSP,我创建了一个类(Class1),其中所有方法都是同步的,以避免使用它时出现问题 在这些用户组的JSP中,我只有一个实例,声明如下: <%! Class1 my_object = null; %> 然后,组中的所有用户将使用同一实例 所以现在,我需要另一个JSP页面,该页面将由用户组2打开,关闭此文件并保存完成的工作 因此,我想我需要获取JSP中

我有一个JSP页面,其中一类用户
users\u group\u 1
需要处理一个文件所有这些方法都使用同一个文件,因此,由于我使用JSP,我创建了一个类(
Class1
),其中所有方法都是同步的,以避免使用它时出现问题

在这些用户组的JSP中,我只有一个实例,声明如下:

<%!
  Class1 my_object = null;
%>
然后,组中的所有用户将使用同一实例

所以现在,我需要另一个JSP页面,该页面将由
用户组2
打开,关闭此文件并保存完成的工作

因此,我想我需要获取JSP中使用的
Class1
实例,并将其提供给第二个实例

我怎么做


额外数据:
user\u group\u 2
从未使用过与
user\u group\u 1
相同的JSP页面,因此我无法使用request/session/。。。对象(我认为)。

您的需求可以通过使用
ServletContext
对象(应用范围)通过下面给出的方法实现

在要初始化对象并将其设置为应用程序范围的第一个jsp页面上

<% 
     ProcessFile processFile=(ProcessFile)application.getAttribute("processFile");
     if(null==processFile){
     // make sure that all method of this class is synchronized beacause of multiple users
         processFile=new  ProcessFile("pathToOpenFile");
     }

     application.setAttribute("processFile", processFile); 
     //now processFile available globally. 
    %>

创建一个单例类,让每个人都获得该类的实例

 public class SingletonFile {
      private static SingletonFile instance.
      static {
            instance = new SingletonFile();
      }

      public static SingletonFile getInstance() {
           return instance;
      }

      private SingletonFile () {}

      // public methods for manipulation of files goes here.
 }

拥有一个负责检索
Class1
实例的类。JSP1和JSP2都使用该类来获取实例,而不是直接创建实例。例如,
class1o=Class1Factory.getInstance()
,其中
getInstance()
是一个静态方法。如果您的目的是返回一个单例,那么该方法可以在第一次调用时创建
Class1
实例,缓存它,并在后续调用中返回缓存的实例。这样做的时候一定要同步。这是个好主意!我应该考虑一下。非常感谢!要做到这一点,您还可以将对象放入应用程序范围,并可以访问任何地方。我尝试使用factory模型,但在这一点上它变得毫无用处,因为它仅在应用程序中为同一客户端(我指的是实例)共享。我现在将尝试@Rajeev所说的应用范围!我能够通过应用范围,谢谢@Rajeev!请把它作为一个答案,这样我就可以接受了。
 <% 
        ProcessFile processFile2=(ProcessFile)application.getAttribute("processFile");
          // now start processing of file 
           if(null!=processFile2){

           processFile2.readFile();
          //open file if not. And read it.  

          //and after that. 
          processFile2.closeFileIfOpen();  
          // do neccesorry checks inside above method while closing file.  
          //all method are synchronized
          }
        %>
 public class SingletonFile {
      private static SingletonFile instance.
      static {
            instance = new SingletonFile();
      }

      public static SingletonFile getInstance() {
           return instance;
      }

      private SingletonFile () {}

      // public methods for manipulation of files goes here.
 }