How do I share object or data between users in web application?
Category: javax.servlet, viewed: 866 time(s).
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 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.example.servlet; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ApplicationContextScopeAttribute extends HttpServlet { public ApplicationContextScopeAttribute() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); context.setAttribute("HELLO.WORLD", "Hello World 123"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } |
And here is what we code in the JSP page to access it.
<%= getServletContext().getAttribute("HELLO.WORLD") %>
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I get servlet request header information?
- How do I get servlet request URL information?
- How do I read servlet context initilization parameters?
- How do I know session last access time?
- How do I get a notification when session attribute was changed?
- How do I capture session creation and removal events?
- How do I invalidate user's session?
- How do I get client IP and hostname in Servlet?
- How do I set the maximum age of a cookie?
- How do I send a response status in servlet?