Java Servlets   «Prev  Next»

Maintaining State using Java Servlets - Exercise

Objective: Write a servlet that counts.

Exercise Scoring

This exercise is worth 5 points. The exercise is auto-scored, which means that all you have to do to receive credit for it is click the Submit button below.

Background and Overview

In this exercise you will write a servlet that counts. You will keep a counter value in the session object, and your doGet() method will retrieve the value, increment it, and display it to the user. In addition, the servlet will display the current time so that you can see different output each time you reload the page.

Download files

You should download the following file from the resources page: session-skeleton.java, a starting servlet that needs your code added.

Instructions

  1. Start with session-skeleton.java, to save you typing. This servlet’s doGet() has three lines of code you may not have seen before:
    Date date = new Date();  
    String time = date.toString(); 
    time = time.substring(11,23);  
    

  2. simply gets the current time into a string called time, so that the output noticeably changes when you reload the page.
  3. Rename session-skeleton.java to Session.java, and add code where the comments tell you. Your code should:
    1. Get a session object from the request
    2. If the session object was null, create a new one and set value to 0
    3. If the session obejct was not null, set value to the session value for “Counter”
    4. increment value
    5. put value back into the session value for “Counter”
    The code already provided will display value (and the current time) to the user.
  4. Compile your servlet, and test it with the JSDK mini-server and a browser as you did in earlier exercises.