I have an action named "Login.action" that puts a certain type of object in the SESSION but depending on this object i want to do something with jQuery this is my example
public String execute() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession sesion = request.getSession();
sesion.setAttribute(user.getprofile(), user);
return SUCCESS;
}
as i said i put an object in my SESSION so i want to acces later on JSP with jQuery
(if the user's profile is "Admin" i want to make an "Admin Panel" button appear using jQuery)
Also i want to know if this is a good way to get this result or there's another (and better) way to do it
Strut set session
Map session = ActionContext.getContext().getSession();
session.put("user","username);
set your user in session
$.session.set("user", $("#uname").val());
get session user
$.session.get('user');
Related
So I am trying to get a servlet to add a Java object to the session of the user, when this servlet is requested. But after the servlet redirects to the next page and I try to retrieve the object, I get a null object instead.
Here is what I do to add the object to the HttpSession (in the servlet):
request.setAttribute("object", obj);
Then I try to retrieve it by (in the JSP):
Object obj = request.getAttribute("object");
So how would I get obj to not be null?
Update:
I have also tried this with nothing:
HttpSession session = request.getSession();
session.setAttribute("object", obj);
with the following in the JSP:
Object obj = request.getSession().getAttribute("object");
Both ways still return null.
You are not adding the object to the session, instead you are adding it to the request.
What you need is:
HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);
In Servlets you have 4 scopes where you can store data.
Application
Session
Request
Page
Make sure you understand these. For more look here
Add it to the session, not to the request.
HttpSession session = request.getSession();
session.setAttribute("object", object);
Also, don't use scriptlets in the JSP. Use EL instead; to access object all you need is ${object}.
A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property.
Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.
If you are going to use the inside servlet do following,
Object obj = new Object();
session.setAttribute("object", obj);
or
HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);
and after setting your attribute by using request or session, use following to access it in the JSP,
<%= request.getAttribute("object")%>
or
<%= session.getAttribute("object")%>
So seems your problem is in the JSP.
If you want use scriptlets it should be as follows,
<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>
Or can use expressions as follows,
<%= session.getAttribute("object")%>
or can use EL as follows,
${object} or ${sessionScope.object}
The request object is not the session.
You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from
HttpSession session = request.getSession(true);
Then you can use setAttribute or getAttribute on the session.
A more up to date tutorial on jsp sessions is: http://courses.coreservlets.com/Course-Materials/pdf/csajsp2/08-Session-Tracking.pdf
OK, I'm kind of inept at explaining my problems, but I'll try to be as detailed, yet concise as possible.
I have 2 servlets;
NewCustomerServlet and
LoginServlet
I have 1 Java bean;
User
The User has a bunch of fields. username, firstName, password, etc...
my index.jsp automatically directs the user to NewCustomerServlet, so the user can create an "account"
Once they finish filling in the fields the User bean is created and saved in the session. Then, the user is able to "login"
The problem I'm having is validating the username from the "user" session with the login.jsp fields using the session.
How do I access the sessions "username" or "password" field. All I can seem to access is the name of the session, which would be "user"?
Referencing the JavaDoc for HttpSession,
You will realize that HttpSession stores attributes by key, just like a HashMap, you would place objects in the session (Any serializeable object) like:
String userName = "something";//
session.setAttribute("username", userName);
Then you can get it back out using:
String un=(String)session.getAttribute("username");
It is possible to store more complex objects, like an entire User object, as long as that object implements Serializable:
User someUser = //details left to the OP
session.setAttribute("user", someUser);
Then you can later retrieve the information for that user:
User someUser = (User)session.getAttribute("user");
if(user != null){
String username = user.getUsername();
}
Also, here is a nice, brief run-through of common session utilization with Servlets and HttpSession: Session Tracking
/****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.
I have performed uploading of a file to a servlet. Now I want to perform some action which will transfer me to another servlet. I have generated some string from this uploaded data and now I need to post it to another servlet which will catch that string from a variable. How to do it?
You can forward (server side) the request to the next servlet:
RequestDispatcher dispatcher = request.getRequestDispatcher("/nexturl");
dispatcher.forward(aRequest, aResponse);
You can attach the decoded variable to your session object and retrieve it from there in the servlet you forward to. (Or, if the servlet can be called with a parameter too, check the session for the variable (remove it when you use it) and if it's not there try to parse the apropriate parameter.)
Update
To use the HTTP session as a way to pass your variable, add it:
HttpSession session = request.getSession();
session.setAttribute("name", "value");
and retrieve it in the next servlet:
HttpSession session = request.getSession();
String value session.getAttribute("name");
session.removeAttribute("name");
The session is created automatically by the servlet container, if uses a session cookie to map session state to a series of HTTP requests from the same browser session.
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);
}
}