在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") %>