When you think about the Security of a web application 'Session Management' is the first thing that strikes in your head. I am now working with an enterprise web application using GWT and you know security is a very vital issue in an enterprise application. And we have ensured the security by managing session data. Here i will describe how to store and retrieve data from session by using GWT RPC.
Suppose you want to store the user name in session after login to the application and check the session value later. Then what do you do?
First create a GWT RPC Service named 'SessionManagementService'. You can give any other name as you like. In SessionManagementService interface add two methods
public void setUserName(String userName); public String getUserName();
And synchronize the methods with 'SessionManagementServiceAsync'.
public void setUserName(String userName, AsyncCallback<Void> asyncCallback); public void getUserName(AsyncCallback<String> asyncCallback);
Now implement the methods in 'SessionManagementServiceImpl'. Let's first talk about the setter method.
public void setUserName(String userName) { HttpSession httpSession = getThreadLocalRequest().getSession(true); httpSession.setAttribute("userName", userName); }
The getThreadLocalRequest method returns you a HttpServletRequest object for the current call. For simultaneous invocation you will get different request object. And the getSession method returns you the current HttpSession for the associated request. So you can get the current session of the current call by getThreadLocalRequest().getSession(true).
The setAttribute method binds an object to the associated session. It stores the object's value as a Name-Value pair. You can put any thing as the value of the object. A String value or List<String> any thing. Here the name of the object is "useName" and the object is bound to this session with this name.
Now come to the getter method.
public String getUserName() { HttpSession session = getThreadLocalRequest().getSession(true); if (session.getAttribute("userName") != null) { return (String) session.getAttribute("userName"); } else { return ""; } }
Get the current session in the same way as described for the setter method. The getAttribute method returns the value of the object which is bound with this session with the specific name. Then simply cast it with your desired type.
Thats all. Just call the services according to your requirement. Play with GWT and stay in touched. :-D