Java如何在Web应用程序的用户之间共享对象或数据?
在Web应用程序中,可以存储对象或数据的作用域类型不同。还有一个page,request,session和application范围。
为了在Web应用程序的用户之间共享数据,我们可以将共享对象放在应用程序范围内,这可以通过调用的setAttribute()方法来实现ServletContext。这样,其他用户可以通过调用的getAttribute()方法来访问数据ServletContext。
让我们看一下简单servlet中的示例代码。
package org.nhooo.example.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApplicationContextScopeAttribute extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("HELLO.WORLD", "Hello World 123");
}
}这是我们在JSP页面中进行访问的代码。
<%= getServletContext().getAttribute("HELLO.WORLD") %>
热门推荐
10 集体生日祝福语简短的
11 婚礼酒祝福语简短大气
12 祝福语闺蜜简短单纯
13 考进高中祝福语简短
14 幼儿祝福语大全简短贺卡
15 简短元宵节祝福语
16 新婚老人祝福语简短大全
17 五一快乐祝福语简短老师
18 孩子新年祝福语简短精辟