Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
9.3 A Servlet Showing Per Client Access Counts
207
Core Approach
Plan ahead: pass URLs that refer to your own site through 
response.encodeURL
 or 
response.encodeRedirectURL
, 
regardless of whether your servlet is using session tracking.
9.3 A Servlet Showing Per Client 
Access Counts
Listing 9.1 presents a simple servlet that shows basic information about the
client's session. When the client connects, the servlet uses 
request.getSes 
sion(true)
 to either retrieve the existing session or, if there was no session,
to create a new one. The servlet then looks for an attribute of type 
Integer
called 
accessCount
. If it cannot find such an attribute, it uses 0 as the num 
ber of previous accesses. This value is then incremented and associated with
the session by 
putValue
. Finally, the servlet prints a small HTML table
showing information about the session. Figures 9 1 and 9 2 show the servlet
on the initial visit and after the page was reloaded several times. 
Listing 9.1 ShowSession.java 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
/** Simple example of session tracking. See the shopping
 *  cart example for a more detailed one.
 */
public class ShowSession extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;
    // Use getAttribute instead of getValue in version 2.2.
    Integer accessCount =
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved