Show TOC

Procedure documentationSetting Cookies in HTTP Servlets Locate this document in the navigation structure

Prerequisites

To be able to set a cookie to the HTTP response object, you must first create it. You do this using the Cookie constructor that takes the cookie name and cookie value as parameters.

Example Example

This example creates a cookie called MyFirstCookie with value of 1.

  1. Cookie sapCookie = new Cookie("MyFirstCookie", "1");
End of the code.

Procedure

You add the cookie to the browser using the addCookie(Cookie cookie) method of the HttpServletResponse object. Before you add the cookie, you can set various attributes to it, such as comments, the maximum time that the cookie can live before it expires, and so on.

Note Note

The cookie attributes that are set using the set- methods of the javax.servlet.http.Cookie class that take parameters of type String should not contain Carriage Return/Line Feed (CR/LF) characters. If CR/LF are found, the AS Java throws com.sap.engine.services.httpserver.exceptions.HttpIllegalArgumentException to indicate the use of the illegal characters.

End of the note.

More information about the methods that you can use to set attributes to a cookie: the documentation of the javax.servlet.http.Cookie class in the Java Servlet 2.5 API specification.

Source Code Source Code

  1. sapCookie.setMaxAge(Integer.MAX_VALUE);
    sapCookie.setComment("Just an example");
    //Add the cookie to the response
    response.addCookie(sapCookie);
    Result
    
End of the code.

Result

The Set-Cookie header is set to your HTTP response headers.