Keammoort
Keammoort

Reputation: 3075

Why is my cookie value not set?

I have a following Java Servlet code executing on Tomcat 7 server. It is supposed to count requests from single browser. This must be done using cookies instead of using SessionAttributes. Code:

@WebServlet("/")
public class CookieTestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        int count = 0;

        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName() == "count") {
                    count = Integer.parseInt(c.getValue());
                }
            }
        }
        ++count;
        resp.addCookie(new Cookie("count", "" + count));
        System.out.println(count);
    }
}

After running this multiple times (refreshing browser) Tomcat console always outputs 1. It seems that no matter how many requests I send, cookie value is always 0. What am I doing wrong?

Upvotes: 0

Views: 274

Answers (1)

Olaf Kock
Olaf Kock

Reputation: 48087

Try to compare the strings like this:

if(c.getName().equals("count"))

Comparing with == tests for identical strings and most likely you're dealing with two different strings that just happen to have the same content.

After this, you'll find out that it might still not work: There's no guarantee for the order of cookies, so you might want to look for the largest value that you get instead of just remembering the last cookie value you saw...

Upvotes: 3

Related Questions