Creating and loading cookies in Java
I'm writing a small webserver in Java, using HttpCore
for most Http requests/responses etc.
HttpCore
and I'm not that familiar with other libraries. Is there an exisiting library (preferably with a working example) to handle cookies?
Edit: I see I was a bit confused regarding the usage of cookies. I'm not completely sure how it works, but I want to keep a session, and to access session variables from the web server. How can I do this? If the browser saves coo开发者_开发问答kies, does it send them to the server? How do I access them?
Session support in a server, is typically built using an object store. A simple object store would be a Map or a Set. The objects in this store ( the values in the case of the Map) have a one-to-one mapping with the concept of a logical session, i.e. for each session created by the server, there will be one item in the store.
Sessions managed by the store may allow for attributes to be associated with them. The list of such attributes may not be known before hand, so you'll need another map for this purpose; the keys would be the attribute names, and the values would be attribute values.
As far as management of the session store is concerned, you'll need to create a new Session in the store, when an API call is made to your server. In simpler words, if a web application decides that it needs to create a session, the server's API must provide the necessary interface to do so. Creating the session object alone is not enough; you'll also need to write the session ID out as a cookie when you first create the session. The API must allow for writing the appropriate response in such a case. You might want to take a look at the Servlet API, specifically for the HttpServletRequest and HttpSession classes, and a servlet container implementation for this purpose.
On the topic of accessing cookies from a request, you'll need to parse the incoming HTTP request headers to check for any cookies sent by the browser. Browsers and other HTTP clients are expected to use the Set-Cookie
request header for this purpose. You'll need to ensure that a session object may be returned to the web application only when a valid cookie is supplied in the request.
精彩评论