user1007522
user1007522

Reputation: 8118

Servlet that counts the visits

I'm new to servlets, had my first lesson today.

Now, I'm trying to create a servlet that counts the visits of a user.

Always getting errors on how I increment the counter:

    HttpSession session = req.getSession(true);
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
synchronized (this) {
    if (!session.isNew()) {
        visitCount = (Integer) session.getAttribute(visitCountKey);
        visitCount = new Integer(visitCount.intValue() + 1); //error
    }
    session.setAttribute(visitCountKey, visitCount);
}

I'm creating a new integer because I've seen here on stackoverflow that integers are immutable. Still it doens't work and gives me an error on that line.

Can someone help me?

Kind regards,

Upvotes: 2

Views: 2439

Answers (4)

Pau Kiat Wee
Pau Kiat Wee

Reputation: 9505

You should add null checking for visitCount

HttpSession session = req.getSession(true);
String visitCountKey = new String("visitCount");
synchronized (this) {

    Integer visitCount = (Integer) session.getAttribute(visitCountKey);
    if(visitCount == null) {
        visitCount = 0;
    }
    visitCount = new Integer(visitCount.intValue() + 1);
    session.setAttribute(visitCountKey, visitCount);
}

Upvotes: 4

HJW
HJW

Reputation: 23453

Should you really decide to do this, you should put the integer visit variable as a static class variable.

public static int VISIT;

public ... doGet(...){ VISIT++; }

Upvotes: 0

Dario Pedol
Dario Pedol

Reputation: 2110

visitCount is null, since you're using isNew() to check if the value was stored already.

Check visitCount for null manually.

From the Docs:

An implementation of HttpSession represents the server's view of the session. The server considers a session to be new until it has been joined by the client. Until the client joins the session, the isNew method returns true. A value of true can indicate one of these three cases:

  • the client does not yet know about the session
  • the session has not yet begun
  • the client chooses not to join the session. This case will occur if the client supports only cookies and chooses to reject any cookies sent by the server. If the server supports URL rewriting, this case will not commonly occur.

Upvotes: 0

Lou Franco
Lou Franco

Reputation: 89242

You are probably getting back a null the first time. Is the error a null reference exception?

You need to check for null and set visitCount to 0.

Upvotes: 1

Related Questions