session in java desktop
anyone know if we can create a session-like mechanism in java desktop application? i am going to develop a java desktop application which has a log-in mechanism to ensure only authorized people can access stored information, then i think if java can something like session, or if there is any mechanism to do something like session. that's all. can somebody开发者_StackOverflow explain?
Basically a session consists of a set of binary or serialized objects, mapped to a session id. Either independently or, most likely, via a Map or Table. So yes, you can implement something like that, by using a smart DB schema. Just be careful about who can see (and use) that DB.
I think, though, your approach is not the best one. After all I think the app will be used by a single user at any time on each machine, so I don't think this is the best approach. Rather you should save the current "session" (AKA app state) in some way, instead of thinking of the session as in the Servlet way.
The session is just a hashmap that is singleton per user . So , you can think that every user has their own hashmap which allows them to store objects. In the servlet , the session is provided by the HttpSession
interface.
The session-like mechanism depends on your application 's architecture .If it is a thick client implementation , which contains only 2 tiers (database tier and the java client) ,and most of the business codes are embedded inside the java application , then every user has their own JVM to run the java code on their machines .Thus , you simply create a singleton hashmap for your desktop application .When the application starts , just initialize this hashmap and put a key and its boolean value to indicate the login status of the user ( e.g. singltonHashmap.put ("LOGIN" , false)
) .Once the user login , you should update the value of the LOGIN key to true to indicate that the user is logged in .
If the java desktop application is thin client implementation , which has an application server to process all the requests from all users, then you can use the stateful session bean
defined by the Enterprise JavaBeans specification (EJB)
.There is an one-to-one mapping between a client and a stateful session bean instance .The application server will makes sure that subsequent method invocations by the same client are handled by the same stateful bean instance . You just declare a hashmap inside an stateful session beans and put the objects that you want to keep track during the conversation in that hashmap. Here is an example for your reference.
精彩评论