java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to send a cookie in Servlet?

A cookie is a piece of information sent to a browser by a Web Server. The browser then returns that information to the Web server. This is how some Web pages "remember" your previous visits; for example, an E-Commerce site might use a cookie to remember which items you've placed in your online shopping cart. Cookies can also store user preference information, log-in data, etc.

Here is an example to send a cookie in the http response object to the client browser.

package com.javacoderanch.example.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WriteCookieExample extends HttpServlet {

	protected void doGet(HttpServletRequest request, 
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
		
        //
        // Send a cookie named username to the client. There are some others
        // properties that we can set before we send the cookie, such as comments,
        // domain name, max age, path, a secure flag, etc.
        //
        Cookie cookie = new Cookie("username", "jduke");
        response.addCookie(cookie);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }
}