Web应用程序中静态对象的范围是什么

What is the scope of a static object in a web application

我有一个应用程序,它包含一个 HTML 表单和一个 Servlet,它根据用户提交的参数创建一个新对象,然后将创建的 bean 添加到列表中。

有JavaBean class:

public class Client{

private String name, adress, tel, email;

public Client(String name, String adress, String tel, String email) {
    this.name = name;
    this.adress = adress;
    this.tel = tel;
    this.email = email;
}

//A bunch of Getters and Setters
}

这里是 ClientsManclass:

public abstract class ClientsMan {

private static List<Client> clientsList;

static
{
    clientsList= new ArrayList<Client>();
}

public static void addClient(Client c)
{
    clientsList.add(c);
}
}

这是处理表单的 servlet 的 doPost() 方法:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //Getting the parametres
    String name = request.getParameter("name");
    String adress = request.getParameter("adress");
    String tel = request.getParameter("tel");
    String email = request.getParameter("email");

    //Creating a Client object from the user inputs
    Client client = new Client(name, adress, tel, email);

    //Adding the bean in an arrayList
    ClientsMan.addClient(client);

}

我需要保留所有添加的客户端的列表以备后用。

我的问题是: 我的应用程序中列表的范围是什么,是请求范围还是应用范围? 用户退出应用后我的列表会丢失吗?

What is the scope of the List in my application, is it a request scope or an Application Scope?

其中

None 因为它的生命周期不由您的应用程序管理,所以 List clientsList 是 class [=] 的 static 字段13=] 这意味着它的范围是初始化 class ClientsManClassLoader,即使在用户退出应用程序后它也应该存在。

静态 class 不是 bean,因为它不是容器管理的,因此没有任何与此 class 相关的作用域。 当用户退出您的应用程序时,您的 List 仍然存在。

如果需要,您还应该管理列表的线程安全。

对象的默认范围将是请求范围。在服务方法中实例化的任何变量都将具有请求范围。每个请求和响应对都是线程的一部分,该线程以服务开始并在服务 class 结束时结束。

话虽这么说,列表是静态类型,所以它将持续到 JVM。但是你会在 运行 时遇到问题,因为它不是线程安全对象。您需要使静态块同步。