Reputation: 15
I want to create a global session in JSP to be used in all Servlets and JSP files as is done in PHP with the instruction:
<?php
session_start ();
?>
Tried with:
HttpSession s = request.getSession ();
and set. It works, but I have to make several passes from one class to another to have it in another JSP file.
How can I do?
Upvotes: 0
Views: 2430
Reputation: 230
You can use ServletContext Listener to maintain the variables for all your application Listener to ServletContext, so you can execute some code when the application starts (is deployed correctly) to initialize the attributes on the ServletContext) and when it finish (before its undeployed).
public final class MyAppListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
System.out.println("Application gets started.");
ServletContext servletContext = event..getServletContext();
servletContext.setAttribute("someAttribute", "Hello world!");
}
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Application has finished.");
}
}
If you're using Java EE 5, you should configure the listener in the web.xml
<listener>
<listener-class>mypackage.listener.MyAppListener</listener-class>
</listener>
Upvotes: 1
Reputation: 845
Try with ServletContext servletContext = event..getServletContext(); then servletContext.getSession(). I think it should work.You need one scope who dies till the end of Application and getSession from that scope.
Upvotes: 0
Reputation: 2373
From tutorialspoint
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows:
<%@ page session="false" %>
You would then use session.setAttribute(name, value)
in your servlets to store session variables and ${name}
(or equivalently <% out.print(session.getAttribute(name)); %>
) to retrieve and output them in your JSPs.
Upvotes: 0
Reputation: 27996
request.getSession()
will create a session the first time it is called, subsequent getSession()
calls will use the same session as long as the session id is available on the URL (or a cookie).
You need to make sure to call response.encodeUrl(...)
when generating links from one page to another so that the session ID is included in the URL.
eg: www.mysite.com/somePage;JSESSIONID=adfasdfasdfasdf
Upvotes: 0