Store an object in session - java

I write the following code to store an object to the HttpSession:
JenaOWLModel jenaOwlModel=MyModelFactory.getJenaModel();
HttpSession session = request.getSession(true);
session.setAttribute("jenamodel", jenaOwlModel);
And get the oject in another servlet through the following code:
HttpSession session = request.getSession(true);
JenaOWLModel model=(JenaOWLModel)session.getAttribute("jenamodel");
It works well, but I want to know if the object I get from the session is the same object I put into the session or it's just a copy . If I change the object I got from the session, whether the object in session will also change? If it changes, will it need to synchronized the object in session by myself.Whether the tomcat provide a mechanism to synchronized the object in session automatically?

If I change the object I got from the session, whether the object in session will also change?
It's the same object, so of course it will change.
If it changes, will it need to synchronized the object in session by myself.
Yes.
Whether the tomcat provide a mechanism to synchronized the object in session automatically?
No.

Related

check if session is valid or not in servlet

/****NOTE****/
in WEB.XML file I am setting session timeout property,
so may be session is expired.
/************/
I am using HttpSession object to manage session
HttpSesion session = myPersonalMethodThatReturnHttpSessionObject();
//I am using Eclipse and it provide me following details in Debug view I put Image Below
//so how can i get value of isValid field or method so here i can put in if condition
if(session != null)
{
//removing attributes from session
}
/*************************************More Description*******************************************/
My Problem is...
note1 --> session timeout is 30 min.
Step1 some one login my web apllication
Step2 session is created.
Step3 if user close web application without signout
Step4 all session attribute is there
Step5 if another user try to login.
Step6 I try to remove all session attribute and store new attribute value.
Step7 Above functionality work properly but, while session is invalidate can't remove session attribute so i need to put condition in if session is valid that remove attribute else do nothing so I need to check session is valod or not.
Since you are seeing isValid=false , I guess your session has become invalid/timedout.
You should be calling HttpSession session = request.getSession(true); or HttpSession session = request.getSession(); to always get the valid session.
The method request.getSession(true) will ensure that it will create a new session if the current session is invalid. If the current session is valid, it will return the same.
The method request.getSession(); by default calls request.getSession(true);.
Based on your update, your login process should be as follows:
HttpSession session = request.getSession(false); // returns null if no session or session is invalid
if(session != null) {
// you have old session
session.invalidate(); // invalidate session - this will remove any old attrs hold in the session
}
// create new session
session = request.getSession(); // creates new empty session
....
You cannot get the isValid field directly. The request.getSession(false) is using it and will return null, if current session is invalid. If session is already invalid you don't have to remove attributes, since they already have been removed and session is inaccessible any more.
you should create an concrete class which implement javax.servlet.http.HttpSessionListener and add your code into its two callback methods:
public interface HttpSessionListener extends java.util.EventListener {
void sessionCreated(javax.servlet.http.HttpSessionEvent httpSessionEvent);
void sessionDestroyed(javax.servlet.http.HttpSessionEvent httpSessionEvent);
}
remember to register your listener in web.xml!
You create session with HttpServletRequest object as follows.
HttpSession session = httpServletRequest.getSession();
This will give you new session if one is not already created or return existing session object.
somewhere in you method myPersonalMethodThatReturnHttpSessionObject() add the following line
HttpSession session = request.getSession(false);
This will help you to find valid session.

Difference between request.getSession().getId() and request.getSession(false)?

What do these calls actually mean in terms of session?
System.out.println("print1: "+request.getSession().getId());
System.out.println("print2: "+request.getSession(false));
OUTPUT
print1: D94146A347D95563186EB7525726336B
print2: org.apache.catalina.session.StandardSessionFacade#d52411
HttpSession session = request.getSession(); Inside the service method we ask for the session and every thing gets automatically, like the creation of the HttpSession object. There is no need to generate the unique session id. There is no need to make a new Cookie object. Everything happens automatically behind the scenes.
As soon as call the method getSession() of the request object a new object of the session gets created by the container and a unique session id generated to maintain the session. This session id is transmitted back to the response object so that whenever the client makes any request then it should also attach the session id with the requsest object so that the container can identify the session.
request.getSession(false) : This method will check whether Session already existed for the request or not. If it existed then it will return the already existed Session. If Session is not already existed for this request then this method will return NULL, that means this method says that the request does not have a Session previously.
In short-
request.getSession().getId() - returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent.
request.getSession(false) - return session object or null if there's no current session.
First line will return the "session id" on server.
The second line will return session object. So what will be printed on system.out would be request.getSession(false).toString();
The default implementation of toString returns the "object id". Object id in terms of session is not the same as session id. Session could be serialized and replicated across the cluster so on each node of the cluster on each JVM it may have it's own object id (but should have same session id).
Calling get session with boolean is explained here:
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession(boolean)
request.getSession()
This method will check for the existing session;if exist its return otherwise create a new session for the request.
request.getSession().getId();
This will return the unique identifier for that session.
request.getSession(false);
This method takes the boolean value.This method check whether there is an existing session present for that user(request);if exist it return that session otherwise it return null i.e it won't create new session.
Just to add more information for session.
request.getSession(true);
This method checks for the existing current session for that user(request) and if the session exist it will return that session or otherwise it create new session for that user.
request.getSession() works like request.getSession(true)
Reference :
http://docs.oracle.com/javaee/1.4/api/javax/servlet/http/HttpServletRequest.html#getSession%28boolean%29
request.getSession().getId()
Returs the id of the session.
Request.getsession(false) returns the already existing session object. It wont return anything i.e. Will return null , if session does not exist. Whereas with true parameter it will create a new session object and return it if no session exists
request.getSession().getId();
Will return unique string id assigned to already started session. Generation of id is vendor specific like apache, jboss etc.
request.getSession(false);
It will return session object associated to particular request if session object is associated it will be returned or it will return null if its is not started by server.
request.getSession().getId();
this will return the id of the an existing session.
Request.getsession(false)
it will return the session if it exists, or it will return null otherwise.
and Request.getsession(false) means : give me the session if it exists, otherwise do not create a new instance (and thus return null).
request.getSession().getId();
returns the unique identifier assigned to this session. And It has return type of String.
request.getSession(false)
returns the HttpSession object if it already exists else return null.

context destroyed, but ths session is still open

I'm new to jsf and I've read that a session can be destroyed
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
fc.getExternalContext().getSessionMap().clear();
session.invalidate();
My problem ist, after doing that the session is still active, with the following bean :
com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap
Do you have an idea?
That's just a new session. To test it yourself, check the value of HttpSession#getId() during the request before and after invalidate. It should be different.
Unrelated to the concrete question, clearing the session map is unnecessary whenever you call invalidate(). The session map will be trashed anyway. Also note that getSession(false) can potentially return null and you'd like to add an extra check to avoid NullPointerException. Or just use getSession(true) instead.

Sending the Session

I am currently doing a system on Google App Engine and am very new to it, I am developing using the Java plattform . I have a problem about sending the session object between servlets. I have already enabled sessions on the appengine.webxml. I can send the session object from my login page to a VIEW page but after which the session object cannot be passed any longer.
Any possible answers?
You do not need to "pass" a session object from one Servlet to another. The session object can always be retrieved via the HttpServletRequest e.g. like this HttpSession session = request.getSession();. In JSPs (I guess that's your view technology) you can access the session via the implicit variable session.
To make sure your session doesn't expire to early set an appropriate value for <session-timeout/> in your web.xml.

What is session in Java? [duplicate]

This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 5 years ago.
So far I understand Httpsession concepts in Java.
HttpSession ses = req.getSession(true);
will create a session object, according to the request.
setAttribute("String", object);
will, bind the 'String', and value with the Session object.
getAttribute("String");
will return an object associated with the string, specified.
What I am not able to understand is: I am creating a session object like
HttpSession ses = req.getSession(true);
and setting a name for it by calling setAttribute("String", object);.
Here, This code resides inside the server. For every person, when he tries to login the same code in the server will be executed. setAttribute("String", object); in this method the string value is a constant one. So, each session object created will be binded by the same string which I have provided. When I try to retrieve the string to validate his session or while logout action taken the getAttribute("String"); ll return the same constant string value(Am I right!!?? Actually I don't know, I'm just thinking of its logic of execution). Then, how can I be able to invalidate.
I saw this type of illustration in all of the tutorials on the WEB. Is it the actual way to set that attribute? Or, real application developers will give a variable in the "String" field to set it dynamically
(ie. session.setAttribut(userName, userName); //Setting the String Dynamically.. I dono is it right or not.)
And my final question is
WebContext ctx = WebContextFactory.get();
request = ctx.getHttpServletRequest();
What do the two lines above do? What will be stored in ctx & request?
HttpSession ses = req.getSession(true); will creates new session means. What value stored in ses.
Some [random] precisions:
You don't need login/logout mechanisms in order to have sessions.
In java servlets, HTTP sessions are tracked using two mechanisms, HTTP cookie (the most commonly used) or URL rewriting (to support browsers without cookies or with cookies disabled). Using only cookies is simple, you don't have to do anything special. For URL re-writing, you need to modify all URLs pointing back to your servlets/filters.
Each time you call request.getSession(true), the HttpRequest object will be inspected in order to find a session ID encoded either in a cookie OR/AND in the URL path parameter (what's following a semi-colon). If the session ID cannot be found, a new session will be created by the servlet container (i.e. the server).
The session ID is added to the response as a Cookie. If you want to support URL re-writing also, the links in your HTML documents should be modified using the response.encodeURL() method. Calling request.getSession(false) or simply request.getSession() will return null in the event the session ID is not found or the session ID refers to an invalid session.
There is a single HTTP session by visit, as Java session cookies are not stored permanently in the browser. So sessions object are not shared between clients. Each user has his own private session.
Sessions are destroyed automatically if not used for a given time. The time-out value can be configured in the web.xml file.
A given session can be explicitly invalidated using the invalidate() method.
When people are talking about JSESSIONID, they are referring to the standard name of the HTTP cookie used to do session-tracking in Java.
I suggest you read a tutorial on Java sessions. Each user gets a different HttpSession object, based on a JSESSIONID request/response parameter that the Java web server sends to the browser. So every user can have an attribute with the same name, and the value stored for this attribute will be different for all users.
Also, WebContextFactory and WebContext are DWR classes that provide an easy way to get the servlet parameters.
As I understand it, your concerns are about separation of the different users when storing things in the HttpSession.
The servlet container (for example Tomcat) takes care of this utilizing its JSESSIONID.
The story goes like this :
User first logs onto website.
Servlet container sets a COOKIE on
the user's browser, storing a UNIQUE
jsessionId.
Every time the user hits the
website, the JSESSIONID cookie is
sent back.
The servlet container uses this to
keep track of who is who.
Likewise, this is how it keeps track
of the separation of data. Every
user has their own bucket of
objects uniquely identified by the
JSESSIONID.
Hopefully that (at least partially) answers your question.
Cheers
Your basic servlet is going to look like
public class MyServlet{
public doGet(HttpServletRequest req, HttpServletResponse res){
//Parameter true:
// create session if one does not exist. session should never be null
//Parameter false:
// return null if there is no session, used on pages where you want to
// force a user to already have a session or be logged in
//only need to use one of the two getSession() options here.
//Just showing both for this test
HttpSession sess = req.getSession(true);
HttpSession sess2 = req.getSession(false);
//set an Attribute in the request. This can be used to pass new values
//to a forward or to a JSP
req.setAttribute("myVar", "Hello World");
}
}
There is no need to set any attribute names for your session that is already done. As others have suggested in other answers, use cookies or URL re-writing to store the sessionID for you.
When you are dealing with the DWR WebContext, it is simply doing the same thing as above, just normally the Request object isn't passed into the method, so you use the WebContext to get that request for you
public class DWRClass {
public doSomething(){
WebContext ctx = WebContextFactory.get();
HttpServletRequest req = ctx.getHttpServletRequest();
HttpSession sess = req.getSession(); //no parameter is the same as passing true
//Lets set another attribute for a forward or JSP to use
ArrayList<Boolean> flags = new ArrayList<Boolean>();
req.setAttribute("listOfNames", flags);
}
}

Categories

Resources