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 红包祝福语简短10字
18 周六早晨祝福语简短