2

Is there a way to convert the session object in scala to the session object in java in Play?

I have a Model method written in java like :

public void DoSomething(Request request, Session session)
{
       String fancyValue = request.getQueryString("userInput");
       session.put("Some Fancy Stuff",fancyValue);
}

and a Controller method written in scala like:

def showHomePage = Action { implicit request =>

     val JRequest = play.core.j.JavaHelpers.createJavaRequest(request)
     val JSession // conversion needed from request.session to play.mvc.Http.Session

     new SomeModel().DoSomething(JRequest,JSession)

     // would this include the updates done to the session in the java model?
     Ok("Testing Stuff").withSession(session) 
}
2
  • Shouldn't that be Ok("Testing Stuff").withSession(/* updated session*/), if you want to persist the session in the client? (Probably not a good idea to save too much data in the session cookie, rather use a handle to server-side cache). Commented Apr 9, 2014 at 11:48
  • @RichardClose I was focusing on something else and forgot that, will edit and include that detail, and I'm using the session to store only a simple Id, so no chance of cramming stuff into it, Thanks :) Commented Apr 9, 2014 at 12:22

1 Answer 1

2

If you look at the docs of the JavaHelpers package, you'll find a function createJavaContext there. You can use that to obtain a play.mvc.Http.Context, from which you can extract a play.mvc.Http.Request and play.mvc.Http.Session.

val java_ctx = play.core.j.JavaHelpers.createJavaContext(request)
val java_request = java_ctx.request()
val java_session = java_ctx.session()
Sign up to request clarification or add additional context in comments.

3 Comments

would updates to the java_session in the model hold if I return Ok("some string").withSession(session) in my controller?
I'm not sure about the conversion, since the Java session is a Java HashMap, but the withSession method needs a Scala Map-like thing as parameter (that is, a sequence of (String, String) tuples. But that conversion aside, yes, they would. But as @RichardClose already mentioned in his comment, you should try to avoid putting too much stuff in there. Best practice is having just some token (a session id) inside the session cookie and do the rest on the server side.
I'm currently using the session only to store an Id, I understand that play uses cookies to store sessions on client side and is limited to 4KB only. I just needed to know how to convert and if updating the session in java would retain the updates in the scala controller.Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.