gpt4 book ai didi

java - 我无法理解该字段是如何保存的(代码有效)

转载 作者:行者123 更新时间:2023-12-01 22:47:03 25 4
gpt4 key购买 nike

我复制了一些代码(示例取自 http://hmkcode.com/java-servlet-send-receive-json-using-jquery-ajax/

它可以工作,但有一些我不明白的事情:我无法理解“文章”如何保留先前的值(value)每次调用 servlet 时是否都会重新初始化?

public class JSONServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// This will store all received articles
List<Article> articles = new LinkedList<Article>();


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

// 1. get received JSON data from request
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String jsonString = "";
if (br != null){
jsonString = br.readLine();
}
ObjectMapper mapper = new ObjectMapper();

Article article = mapper.readValue(jsonString, Article.class);

response.setContentType("application/json");

articles.add(article);

mapper.writeValue(response.getOutputStream(), articles);


}
}

最佳答案

应用程序服务器通常维护 servlet 的单个实例,因此声明 List<Article> articles Servlet 类中的 as 属性将用作文章的整个应用程序的容器。

请注意,此方法应该仅用于测试目的。像这样设计的实际应用程序将会失败,因为 servlet 同时被多个线程访问,并且同一 URL 上有多个请求通过您的 servlet 尝试将数据添加到此不同步列表中将引发 ConcurrentModificationException .

如果您想要/需要存储每个客户端(浏览器)的数据,请使用 session 范围。如果您想要/需要存储每个应用程序的数据(可供应用程序的所有客户端使用),请使用应用程序范围。

更多信息:

关于java - 我无法理解该字段是如何保存的(代码有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com