How can I get all active sessions in a jax-rs application? - java

I know how to get the caller Session, I inject the servlet request and get the Session object from it, but I don't know how to get the other callers sessions.
#Context
HttpServletRequest request;
...
Session session = request.getSession();
// Session[] a = request.getAllSessions(); // this would be great

Related

Session Handling in servlet using JSESSIONID cookie not getting session

I read that to persist session in servlet a cookie gets saved at client side with the name of JSESSIONID.I checked it also and I found the cookie of localhost with the name of JSESSIONID with some random String value.
So I tried to create the session manually by creating the JSESSIONID cookie in the servlet but when I am trying to get the session it's not working.
What is happening here?
Is there anything else other than cookie(JSESSIONID) that gets stored soomewhere for the session creation? If not why I'm not able to get the session ?
Please Help.
Code that I used to create the cookie and get the session
package sessionHandling;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet("/sessionhandling")
public class SessionHandling extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
out.print("Hello Mr.! How are you?");
HttpSession session = request.getSession(false);
if(session != null){
out.println("You are logged in.");
out.println("session found with "+session.getId());
out.println("session found with "+session.getLastAccessedTime());
}else{
//session = request.getSession(true);
Cookie JSESSIONID = new Cookie("JSESSIONID", "12345");
JSESSIONID.setMaxAge(-1);
response.addCookie(JSESSIONID);
System.out.println("Cookie Created");
out.print("You are not logged in");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
You're not responsible for creating or tracking the cookie. The servlet container looks after this for you.
As soon as you invoke:
HttpSession session = request.getSession(true);
or
HttpSession session = request.getSession();
then the servlet container will start maintaining the session for you (and generate the cookie as needed).
The HttpSession object is maintained in server memory between requests and is usually looked up by the session id. If you create the cookie yourself the server will not know anything about it or any associated HttpSession.
Once you run your code , first time , session will be null and you will instruct the browser (or any other client) to create the JESSIONID cookie. Till here it is all correct.
Now, when you make the request again, browser (or any other client) will attach the cookie to the request and tomcat (or any other servlet engine) will receive the JESSIONID. Till here it is all fine.
But what now ? Tomcat (or any other servlet engine) will then search if it has any HttpSession object having sessionID "12345". Do you think it will be found ? No.
Why ? The code that you wrote above was only to Set cookie header in response message. It did not instructed tomcat(or any other servlet engine) to view this JSESSIONID named cookie as a session Id and create a corresponding HttpSession Object internally in Java Heap.
That's why we use request.getSession(). It instructs tomcat to do 2 things -
Whatever you did i.e. add the Set Cookie info in response by name JSESSIONID with a random ID.
Creates a corresponding HttpSession object and save it in memory (by default), so that next time when request comes, it can recognise that JESSIONID as a valid session ID by finding a corresponding HttpSession object. This was missed by your code.

Unable to get session.getAttribute in RequestMethod.POST

I have tow method and using Spring MVC, first is a method=RequestMethod.GET and there I set session.setAttribute("clientId", "abc").
Second method is a method=RequestMethod.POST where I do this:
HttpSession session = request.getSession();
System.out.println("-----" + (String)session.getAttribute("clientId"));
But always get null.
[Edit]
The thing here is the post method is not called by ModalandView("postpage"), its called by Http callout by Apache oltu internally
In Get method do
Session session = request.getSession(true);
session.setAttribute("clientId", "abc");
In Post do
String s = request.getSession().getAttribute("clientId");

Forward inside tomcat webapp: sessions are not expired

I have a webservice that does quite simple a forward to another webapp located on the same Tomcat container.
private Response forward(
#Context ServletContext context,
#Context HttpServletRequest request,
#Context HttpServletResponse response){
ServletContext ctx = context.getContext("/myothewebapp");
RequestDispatcher dispatcher=ctx.getRequestDispatcher("/test");
dispatcher.forward(request, response);
return Response.ok("").build();
}
This works as desired except the fact, that the sessions of this webapp are not being expired. In the tomcat manager you can see, that the opened sessions get accumulated quite fast, up to several hundreds of them.
I am not sure why they last when the response is already sent.
Any ideas what is missing in my forward-method?
Why they last when the response is already sent.
Why you think that session will be invalidated after response will be sent.
It will only be invalidated if session timeout occurs or you forcefully invalidate the session using :
Session#invalidate() method

In JSF HttpServletRequest object getAttribute() returning Null

I have Two different JSF page Let Us suppose A.jsf and B.jsf But Both calling same managed bean different methods ManagedBean.java
A.jsf is calling a SessionScoped Managed bean method where i set some attribute in Request class object
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.setAttribute("token", requestToken.getToken());
request.setAttribute("tokenSecret", requestToken.getTokenSecret());
Then redirecting some other side like this
response.sendRedirect(requestToken.getAuthorizationURL());
Now after successful login i am opening another JSF page of my website suppose b.jsf and from this page i am calling method like this
<f:event listener="#{ManagedBean.redirectLogin2}" type="preRenderView" />
and calling same Managedbean but another method
public String redirectLogin2() throws TwitterException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
}
But when i am doing in above method redirectLogin2()
request.getAttribute("token")
request.getAttribute("tokenSecret")
Both giving Null. What cab be the issue here?
Request scoped attribute life span will be lost on sendRedirect. You should set value on session scope.
HttpSession session=request.getSession();
session.setAttribute("token", requestToken.getToken());
session.setAttribute("tokenSecret", requestToken.getTokenSecret());
After setting value to session. You can access that from request like
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().getAttribute("token");
request.getSession().getAttribute("tokenSecret");
Although, above code will work but that is not good practice. JSF has #SessionScoped annotation which will make available of your variable access with login session.

How to get session information in Spring MVC 3

I am new to spring MVC and I am trying to get the session information in my controller class
Right now I am using
HttpSession objHttpSession = request.getSession(true);
if I want to get session creation time and session Id I am using
objHttpSession.getCreationTime();
objHttpSession.getId();
I want to know is there any spring MVC specific way to get the session details?
Thanks in advance
I usually declare a parameter of type HttpSession in my Spring MVC controller method when I need to access session details.
For example:
#RequestMapping("/myrequest")
public void handleMyRequest(HttpSession session, ...) {
...
}
I think it's the simplest way, but don't know if it fits your needs.
You can get the session in Spring MVC like this:
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();
The currentRequestAttributes method return the RequestAttributes currently bound to the thread in which there is a current request and from that request you can get the session. This is useful when you need to get hold of the session in non-spring class. Otherwise you can just use:
#RequestMapping(...)
public void myMethod(HttpSession session) {
}
Spring will inject HttpSession instance into your controller's method.

Categories

Resources