In a web application there are different type of scope where we can store object or data. There are a page
, request
, session
and application
scope.
To share data between users of the web application we can put a shared object in application scope which can be done by calling setAttribute()
method of the ServletContext
. By this way data can then be accessing by other users by calling the getAttribute()
method of the ServletContext
.
Let’s see the example code in a simple servlet.
package org.kodejava.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "SharedObjectServlet", urlPatterns = "/shared-object")
public class ApplicationContextScopeAttribute extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("HELLO.WORLD", "Hello World 123");
}
}
And here is what we code in the JSP page to access it.
<%= request.getServletContext().getAttribute("HELLO.WORLD") %>
Maven dependencies
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023