Java Reference
In-Depth Information
On the server side, things are much simpler, as you'll see in Listing 10-5. If you're writing
Java servlets, you don't even have to worry about cookies. Instead, you just deal with an
HttpSession object. The code that follows shows a servlet that interacts with CookieMIDlet ; it
implements a session-based hit counter. It's been tested on Tomcat 5.5 but should work fine
on other servers. Note that you will have to map the URL used by the MIDlet to this servlet
class; for details, see an introductory topic on servlets or your server's documentation.
Listing 10-5. A Simple Session Handling Servlet
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class CookieServlet extends HttpServlet {
private Map mHitMap = new HashMap();
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String id = session.getId();
int hits = -1;
// Try to retrieve the hits from the map.
Integer hitsInteger = (Integer)mHitMap.get(id);
if (hitsInteger != null)
hits = hitsInteger.intValue();
// Increment and store.
hits++;
mHitMap.put(id, new Integer(hits));
String message = "Hits for this session: " + hits + ".";
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
}
}
The servlet retrieves the HttpSession object. Then it pulls out the session ID and uses it as
a key into a map of hit counts. After retrieving and incrementing the hit count for the session,
the servlet sends it as the response back to the MIDlet. You can start up multiple copies of the
Search WWH ::




Custom Search