My JSP contains javascript code,which include two function
One function is call a servlet
ie.window.showModalDialog("mams.openAndSave",...........)
for opening a report and setting a value in HttpSession.
And Another function use retrieve session value set previously using expression language
ie.dataToSave='${sessionScope.executionFilePath}';
but here dataToSave variable have not been initialized during form submission.
Above functions are called dynamically using link provided in JSP.
Any one know solution to this query,please reply
First of all, you need to control the flow of your Javascript call. You can read about <body onload="myFunction()"> and document.ready features to control the javascript function calls.You cannot directly access session objects using client side javascript directly. The session objects can be accessed with the help of ajax call to a servlet or any server side programs. Thus, the servlet access the HttpSession, sets the attribute value, gets the attribute value and return it to the client. HttpSession is not threadsafe by default. so, you can make it thread safe by locking the session object in the servlet or server side program as below
HttpSession session=request.getSession();
synchronized(session)
{
//setAttributes in the session object
//getAttributes from the session object
}
Hope this helps
Related
I read lot of articles which says that there are different ways to manage the session like cookies, hidden form fields, url rewriting and jsessionId.
But when I do
HttpSession session = request.getSession();
Which method is actually used internally?
According to the servlet 2.4 specification:
Session tracking through HTTP cookies is the most used session
tracking mechanism and is required to be supported by all servlet
containers... To fulfill this requirement, Web containers commonly
support the URL rewriting mechanism.
Basically the session tracking (i.e. to keep the user interaction and sending the data ) can be maintained by 4 ways like HttpSession,cookies,hidden field and URL rewriting.
It depends on your requirement , which it needs to use.
If you are using HttpSession then you need to go for
HttpSession session = request.getSession(true);
As Cookies are client side.
Hidden fields are the form data you need to send to by request to servlet.
URL rewriting is used for sending the data using href or any link (usally GET method).
Session is used for secure and state full transaction.
Which method is actually used internally?
Its recommended to use HttpSession , if you want to track the request data over the application, until unless you invalidate that session. Jsessionid is a part of HttpSession. Internally Session is using unique Jsessionid for each session you are creating.
Hope it will help you.
The answer is that it doesn't depend on Java. It depends on the specific servlet container you are using and possibly the browser as well. If the brower won't accept cookies for example the container may be forced back to using URL rewriting.
I'm developing a single page jQuery & Backbone.js web app. The backend is a JBoss 6 application server.
Until now we had the following structure:
There is only one servlet (front controller). Every request from the JavaScript client goes through here.
In the servlet - at the first request of a certain JS client - I make a look p to a stateful session bean. For the next requests of this client, I store the result of the look up in an HTTP session container. So every JS client has exactly one stateful session bean. This connection is kept by a session cookie.
Now I have an additional requirement:
When the user has two browser tabs (in one browser), they should have two isolated instances of the web app in every browser tab. Because of that I have a problem with session cookies because this session cookie is for all browser tabs.
I have to change the structure so that:
The servlet has to generate a new session ID for the first request of a certain JS client. This session ID is communicated to the client.
With every POST to the backend the JS client has to send this session ID.
My question is:
Until now I saved the result of the look up in an HTTP Session object and I hadn't to think about generating a session ID. But now I have to store this somewhere else, where?
Has anybody experience with this kind of setting and can help me?
Update:
Thank you BalusC for this very interesting approach.
When I understood you well, this means:
All individual JS clients of the tabs of one browser share one HTTP session object. And in this HTTP session object, every tab has its own entry point. That sounds really good. So I still can use the whole HTTP session infrastructure and don't have to reinvent the wheel.
Autogenerate an unique value on the initial GET request which you store and pass around on every subsequent postback as a hidden input value. Use this unique value as identifier of the session attribute representing the view-scoped data.
During the 1st request on a brand new session, do:
Map<String, ViewData> viewScope = new HashMap<String, ViewData>();
session.setAttribute("viewScope", viewScope);
(the ViewData represents the view-specific data you'd like to track across postbacks on the same view)
During every GET request, do:
String viewDataId = UUID.randomUUID().toString();
viewScope.put(viewDataId, new ViewData());
request.setAttribute("viewDataId", viewDataId);
During generating the HTML, do:
<input type="hidden" name="viewDataId" value="${viewDataId}" />
During every POST request, do:
ViewData viewData = viewScope.get(request.getParameter("viewDataId"));
// Get/set view-specific data in there.
Make sure that jQuery also passes this hidden input around (which shouldn't be a big problem if you already properly use $(form).serialize() or e.g. AjaxForm plugin to ajaxify the forms).
If you're familiar with Java EE's MVC framework JSF, then it may be useful to know that its #ViewScoped annotation works roughly the same as described above. See also a.o. How to choose the right bean scope?
You can use session tracking with URL rewriting. See here:
Session shared in between tabs
I have my flex object embedded to JSP page.The JSP page retrieves user information like user name and group from portal profile object and stores in http session parameters. The flex Object makes a remote call to Employee.class to perform persona based operation.
I retrieved the session id in JSP and also in the Employee.class both are same. But I am not able to retrieve the username stored in the http session from FlexSession. I read in the internet that the FelxSession will hold all httpSession information as well. It’s always coming as null. Correct me if I am wrong.
In the JSP I set the
session.setAttribute("sasUserName","sasdemo");
session.setAttribute("sasGroupList",gl);
In Employee.class
import flex.messaging.FlexSession;
import flex.messaging.FlexContext;
mySession = (FlexSession)FlexContext.getFlexSession();
mySession.getAttribute("sasUserName")
Let me know if I need to make any other set up.
FlexContext should be called only inside of a blazeds AMF request - otherwise all the content is null. What happens is:
a)an AMF call is invoked
b)the MesageBroker servlet will setup the FlexContext object
c)the invoked method is executed
d)the MessageBroker servlet will clear the FlexContext object
e)the result of the call is returned.
Let me know if it's clear enough.
Is HttpSession in java servlet is created only after
HttpSession s = request.getSession();
?
In my code I didn't write that, but when I use if (request.getSession(false) == null) ..., it doesn't work. Why?
A HttpSession is created when calling request.getSession().
But if you access a JSP by default it will automatically create a session.This behaviour can be disabled by using: <%# page session="false">
Are you using JSP?
Read JavaDocs, it says clearly:
This says, request.getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
And the other variant request.getSession(isCreate)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Update
On a bit research, I have found that Session is not created unless request.getSession() is called somewhere. Since, The servlet container uses this interface to create a session between an HTTP client and an HTTP server. There are good chances that your Servlet container creates the Session for you by default.
refer:
Java Doc HttpSession
Discussion on JavaRaunch: is HttpSession created automatically?
But, to be safer side, use request.getSession() to get session, and use request.getSession(false) only when you need to verify if a session has already been created.
In addition to Nishant's answer note that session can be created implicitly by JSP pages unless you configured them not to create a session with <%# page session = "false" %>.
To make it complete:
session is not created, unless you call request.getSession(), in your servlet, use request.getSession(false) to get existing session without creating new session
if you use JSP page, session is automatically created for you - variable session - unless you specify <%# page session="false" %>
even if your session is created automatically, you can use session.isNew() to find out, if it has been newly created
Try to remove session cookies from browser and make another test. If it does not work then some other component is creating a new session before that call.
How is a session object attached to each thread of a servlet? I believe its not a ThreadLocal, so how is it attached to each servlet thread?
It's not attached to the Servlet thread, it's attached to the HttpServletRequest. Each invocation of the Servlet is passed a HttpServletRequest and an HttpServeltResponse. So, they're just local variables to the Servlet instance -- nothing to do with the thread.
A JSESSIONID variable gets set in the client's cookie (or URL sometimes) and the container uses the JSESSIONID to look up the appropriate session for the given request.