Personal notes on Java
For other technologies like HTML, CSS, .NET, PHP, etc. check my other blog

Download examples

  • Form with 2 mandatory fields. This example uses 2 forms: one submits a form the other gets and displays the form's results.
    If the user fails to supply a value for any of the fields in the form, it re-displays the form but with an error message saying that the value is missing. Doesn't make the user reenter values that they’ve entered already.
    Download source code
  • Servlet with a counter:
    When the counter hits number 10 the servlet redirects to "nytimes" site, otherwise the counter redirects to "washingtonpost" site.
    NOTE: dont forget to synchronize access to shared resources (the counter).
    Download source code
     
  • Idea: generate list of large (e.g., 150-digit long) prime numbers
    – Show partial results until completed (if two users submit the same input, the last one will start with the numbers already returned to the first user);
    – Let new clients make use of results from others (the program keeps a ArrayList with the last 10 results of prime numbers);
    Demonstrates:
     - use of the Refresh header.
     - how easy it is for servlets to maintain state between requests.
     - that servlets can handle multiple simultaneous connections - each request is in a separate thread.
    Download source code
    [4]
     
  • Visits count using cookies. Things to test with this app:
          - Open 2 distinct browsers (ex. firefox and chrome) and check that each one gets their own count
          - The cookie has a maxAge time set to 10 seconds, so it will persist in the client and if you close and re-open a browser before the 10s end it will keep counting. If you wait more than 10 seconds from each request the cookie will be destroyed and, so, the counter will start from zero again
    (remember maxAge has this special values:
                 -"-1" means the cookie will exist till the session expires (the client close the browser;
                 - "0" means destroy the cookie;
                 - any value >0 means the cookie will be destroyed when that time expires;
    Download source code [5]
  • MVC (aka "Model 2") example with servlets+jsp [7]

Solutions to common problems [4]

A way to store data between requests:
– For data that is not specific to any one client, store it in a field (instance variable) of the servlet;
– For data that is specific to a user, store it in the HttpSession object;
– For data that needs to be available to other servlets or JSP pages (regardless of user), store it in the ServletContext;

A way to keep computations running after the response is sent to the user.
– This task is simple: start a Thread. The only subtlety: set the thread priority to a low value so that you do not slow down the server.

A way to get the updated results to the browser when they are ready.
– Use the Refresh HTTP header to tell browser to ask for updates


NOTE: HTTP headers can become very useful when working with servlets. Check the HTTP page to check some of them.


Useful Annotations and XML descriptors

Check the "Servlet Annotations" section on the annotations page.

Useful Classes/Interfaces and their methods

abstract class HttpServlet


Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP DELETE requests
  • init and destroy, to manage resources that are held for the life of the servlet
  • getServletInfo, which the servlet uses to provide information about itself

interface ServletRequest

Defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method.
A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.
  • void setAttribute(java.lang.String name, java.lang.Object o)
    Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher.
    Ex.: request.setAttribute("selectedCategory", selectedCategory);
     
  • RequestDispatcher.getRequestDispatcher(java.lang.String path) 
    Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
    Ex.:
    try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

interface HttpServletRequest extends ServletRequest

Extends the ServletRequest interface to provide request information for HTTP servlets.
The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
Useful methods:
  • String getServletPath()
    Returns the part of this request's URL that calls the servlet.
    Ex.:
    String userPath = request.getServletPath();
    if (userPath.equals("/category")) { ...
     
  • Methods for operating with the headers sent by the client (see the "Managing HTTP headers with Servlets" section below on this page):
     - getHeader (header name is not case sensitive)
     - getHeaders
     - getHeaderNames
     
  • Specialized methods:
     - getCookies
     - getAuthType and getRemoteUser
     - getContentLength
     - getContentType
     - getDateHeader
     - getIntHeader
  •  Other methods:
    - getMethod
     - getRequestURI
     - getQueryString
     - getProtocol
     
  • String getQueryString()
    Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
    Ex.: String categoryId = request.getQueryString();
     
  • HttpSession getSession()
    Returns the current session associated with this request, or if the request does not have a session, creates one.
    Ex.: Inside a servlet we could do:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();
    ShoppingCart cart = new ShoppingCart();
    //set a session attribute
    session.setAttribute("cart", cart);
    //retrieve an object from a session attribute
    ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
    (...)
    

interface HttpServletResponse extends ServletResponse

Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.
The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
Usefull methods:
  • response.setStatus(int statusCode)
    Usefull to set HTTP response header codes.
    Use a constant for the code, not an explicit int: constants are in HttpServletResponse (ex.: SC_OK, SC_NOT_FOUND)

    Most important HTTP status codes:
    – 200 (default)
    – 302 (forwarding; set with sendRedirect)
    – 401 (password needed)
    – 404 (not found; set with sendError)
     
  • response.sendError(int code, String message)
    Wraps message inside small HTML document. Usefull to send 404 error pages.
     
  • response.sendRedirect(String url)
    Redirects the client to a new URL. Sets the Location header (plus changes status code to 302).
    Ex.:
    response.sendRedirect("somPage.xhtml");
     
  • response.getWriter()
    Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1.
    Calling flush() on the PrintWriter commits the response.
    Either this method or getOutputStream() may be called to write the body, not both.
    Ex.:
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");

     
  • response.setHeader(String headerName, String headerValue)
    Sets an arbitrary header
     
  • response.setDateHeader(String name, long millisecs)
    Converts milliseconds since 1970 to a date string in GMT format;
     
  • response.setIntHeader(String name, int headerValue)
    Prevents need to convert int to String before calling setHeader
    Ex.:
    if (!isLastResult) {
        //make the client poll the server again in 5 seconds:
        response.setIntHeader("Refresh", 5); 
    }
  • addHeader, addDateHeader, addIntHeader
    Adds new occurrence of header instead of replacing
     
  • setContentType
    Sets the Content-Type header. Servlets almost always use this. See a table of common MIME types:  or google for it.
    Ex.: Servlet that creates Excel spreadsheet comparing apples and oranges:
    @WebServlet("/apples-and-oranges")
    public class ApplesAndOranges extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("application/vnd.ms-excel");
            PrintWriter out = response.getWriter();
            try {
                out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");
                out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
                out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
            } finally {
                out.close();
            }
        }
    }
  • setContentLength
    Sets the Content-Length header. Used for persistent HTTP connections. See Connection request header.
     
  • addCookie
    Adds a value to the Set-Cookie header. See separate section on cookies.

Managing HTTP headers with Servlets

A typical HTTP Request looks like this:
GET /search-servlet?keywords=servlets+jsp HTTP/1.1
Accept: image/gif, image/jpg, */*
Accept-Encoding: gzip
Connection: Keep-Alive
Cookie: userID=id456578
Host: www.somebookstore.com
Referer: http://www.somebookstore.com/findbooks.html
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)

Usefull stuff:
  •  NOTE: Always check that request.getHeader is non-null before trying to use it:
    String val = request.getHeader("Some-Name");
    if (val != null) {
    …
    }
  • The HTTP headers are optional, so you cannot expect that they are always sent by the client browser. The code bellow can be used to show all the headers and their values sent by the client:
    String html = "";
    Enumeration<String> headerNames = request.getHeaderNames();
    String headerName;
    while (headerNames.hasMoreElements()) {
        headerName = headerNames.nextElement();
        html += "<tr>"
                + "<td>" + headerName + "</td>"
                + "<td>" + request.getHeader(headerName) + "</td>"
                + "</tr>"; 
    }
    
  • Checking which browser the client is using (checks for Microsoft IE):
    String userAgentHeaderValue = request.getHeader("User-Agent");
           if(userAgentHeaderValue.contains("MSIE")){...}
  • Checking if the client came to this page from the expected page and, if not, redirect him back:
    String refererHeaderValue = request.getHeader("referer");            
        if(refererHeaderValue == null ||
           !refererHeaderValue.contains("TutorialServletJSP/tutorial4ex3.xhtml")) {
                response.sendRedirect("tutorial4ex3.xhtml");
        }
    

The next servlet is automatically started up with the application and defines many urlPatterns that it will manage:
@WebServlet(name = "ControllerServlet", loadOnStartup = 1, urlPatterns = {
    "/category",
    "/addToCart",
    "/viewCart",
    "/updateCart",
    "/checkout",
    "/purchase",
    "/chooseLanguage"})
public class ControllerServlet extends HttpServlet {

The init() method: the web container initializes the servlet by calling its init method. This occurs only once, after the servlet is loaded and before it begins servicing requests.

Example: we want to load all categories only once on application startup and make them available trough the application life cycle (instead of always querying the DB everytime), so we can use the init method to store the data in an application-scoped attribute [1]

public void init() throws ServletException {

        // store category list in servlet context
        getServletContext().setAttribute("categories", categoryFacade.findAll());
}

Scoped variables [2]:
When working with JSP/Servlet technology, there are four scope objects available to you within the realm of the application. JSP technology implements implicit objects that allows you to access classes defined by the Servlet API.
NOTE: another way (explained on the web.xml notes page) of sharing variables is by Setting Context Parameters [3]
ScopeDefinitionServlet Class JSP
Application Global memory for a web application. Data is shared amoung different clients and servlets. javax.servlet.ServletContext
synchronized(this) {
SomeBean value = SomeLookup.findResult(...);
getServletContext().setAttribute("key", value);
RequestDispatcher dispatcher =
request.getRequestDispatcher
("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
}
NOTE: you need to synchronize when using the application scope (beacause the benan will be shared with other users).
Implicit object: application
JSP 2.0:
${key.someProperty}
JSP 1.2:
<jsp:useBean id="key" 
    type="somePackage.SomeBean"
    scope="application" />

<jsp:getProperty 
    name="key" 
    property="someProperty" />
Session Data specific to a user session. Data is stored in session and can be accessed from the same client within the same session. javax.servlet.http.HttpSession
SomeBean value = LookupService.findResult(...);
HttpSession session = request.getSession();
session.setAttribute("key", value);
RequestDispatcher dispatcher =
request.getRequestDispatcher
    ("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
Implicit object: session
JSP 2.0:
${key.someProperty}
JSP 1.2:
<jsp:useBean 
    id="key" 
    type="somePackage.SomeBean"
    scope="session" />

<jsp:getProperty 
    name="key" 
    property="someProperty" />
Request Data specific to an individual server request. Data is only acessible for the current client and the current request. javax.servlet.HttpServletRequest
SomeBean value = LookupService.findResult(...);
request.setAttribute("key", value);
RequestDispatcher dispatcher =
request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
Implicit object: request
Using scripplets/expressions:
<%= request.getAttribute("key");
JSP 2.0:
${key.someProperty}
JSP 1.2 (Old!):
<jsp:useBean
    id="key" 
    type="somePackage.SomeBean"
    scope="request" />

<jsp:getProperty 
    name="key" 
    property="someProperty" />
PageData that is only valid in the context of a single page (JSPs only)[n/a] Implicit object: page

Examples:
  • set/get a application-scoped variable in a Servlet:
    // store category list in servlet context
    getServletContext().setAttribute("categories", categoryFacade.findAll());
    //get category list from servlet context
    List <Category> list = (List<Category>) getServletContext().getAttribute("categories"); 
    access the variable from JSP (used in a forEach statement in this example):
    <c:forEach var="category" items="${applicationScope.categories}">
  • set/get a session-scoped variable in a Servlet:
    HttpSession session = request.getSession();
    // place selected category in session scope
    session.setAttribute("selectedCategory", selectedCategory);
    
    access this variable  in JSP:
    ${sessionScope.selectedCategory.name}
  • set/get a page-scoped variable in JSP (this variables are only accessed by JSP):
    <!-- set the variable -->
    <c:set var="myVar" value="Hello World" />
    <!-- get the value-->
    ${pageScope.myVar}
When referencing scoped variables in JSP using EL expression, you do not need to specify the variable's scope (provided that you do not have two variables of the same name in different scopes). The JSP engine checks all four scopes and returns the first variable match it finds. In category.jsp for example, the expression:
${categoryProducts}
is shorthand for:
${sessionScope.categoryProducts}
Why scoped variables? Although you can access the database from the application by configuring a data source on GlassFish, adding a resource reference to the application's deployment descriptor, and using JSTL <sql> tags in the application's JSP pages to quickly set up prototypes that include data from the database, <sql:query var="categories" dataSource="jdbc/affablebean">     SELECT * FROM category </sql:query> this is not a realistic scenario for medium to large-sized applications, or applications managed by a team of developers, as it would prove difficult to maintain or scale. Furthermore, if you are developing the application into multiple tiers or are adhering to the MVC pattern, you would not want to keep data-access code in your front-end. Using Enterprise beans with a persistence model enables you better conform to the MVC pattern by effectively decoupling the presentation and model components: by using session and entity beans you can remove any JSTL data access logic and instead utilize the data access methods provided by the session beans, and store the data in scoped variables so that it can be retrieved from front-end page views. Examples: Example 1: The next code stores a list in an servlet scoped atribute
@Override
public void init() throws ServletException {
    // store category list in servlet context
    getServletContext().setAttribute("categories", categoryFacade.findAll());
}
This variable "categories" can then be accessed in JSP like this:
<div id="indexRightColumn">
    <c:forEach var="category" items="${categories}">
        <div class="categoryBox">
            <a href="category?${category.id}">
                <span class="categoryLabelText">${category.name}</span>               
                <img src="${initParam.categoryImagePath}${category.name}.jpg" alt="${category.name}"/>
            </a>
        </div>
    </c:forEach>   
</div>
Example 2: the next code sets variables ("selectedCategory" and "categoryProducts") in the request scope:
 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();
        Category selectedCategory;
        Collection<Product> categoryProducts;

        // if category page is requested
        if (userPath.equals("/category")) {
            // get categoryId from request
            String categoryId = request.getQueryString();

            if (categoryId != null) {
                // get selected category
                selectedCategory = categoryFacade.find(Short.parseShort(categoryId));

                // place selected category in request scope
                request.setAttribute("selectedCategory", selectedCategory);

                // get all products for selected category
                categoryProducts = selectedCategory.getProductCollection();

                // place category products in request scope
                request.setAttribute("categoryProducts", categoryProducts);
            }
this variables can then be accessed in JSP, for example, like this:
<c:forEach var="product" items="${categoryProducts}" varStatus="iter">
            <tr class="${((iter.index%2)==0) ? 'lightBlue': 'white'}">           
                <td>
                    <img src="${initParam.productImagePath}${product.name}.png" alt="product image">
                </td>
                <td>
                    ${product.name}
                    <br>
                    <span class="smallText">${product.description}</span>
                </td>
                <td>${product.price}</td>
                <td>
                    <form action="addToCart" method="post">
                        <input type="hidden"
                               name="productId"
                               value="${product.id}">
                        <input type="submit"
                               value="add to cart">
                    </form>
                </td>
            </tr>
        </c:forEach>

Session Tracking Options

There are three conventional ways of tracking sessions between client and server [2] see ref [6] for the Java Session Tracking Api:

  1. By far the most common is with cookies.
  2. URL rewriting can be applied in the event that cookies are not supported or disabled.
  3. Hidden form fields can also be used as a means of "maintaining state" over multiple requests, but these are limited to usage within forms.

Usually you use the Java Session Tracking API to automate this [6]:
HttpSession request.getSession(): gets an HttpSession object (this is a hastable associated with the user, i.e., contains key-value pairs)


The Servlet API provides a high-level mechanism for managing sessions. Essentially, it creates and passes a cookie between the client and server with each request-response cycle. If the client browser doesn't accept cookies, the servlet engine automatically reverts to URL rewriting.
Summary notes:
Sessions do not travel across network, only unique identifier does
Get the session: request.getSession()
Extract data from session: session.getAttribute
 - Note: Do typecast and check for null; If you cast to a generic type, use @SuppressWarnings;
Put data in session: session.setAttribute
Custom classes in sessions: Should implement Serializable

interface HttpSession

(see ref [2] for introductory examples and explanation see ref)
Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

This interface allows servlets toView and manipulate information about a session, such as the session identifier, creation time, and last accessed timeBind objects to sessions, allowing user information to persist across multiple user connectionsHttpSession object to identify users over multiple requests.

An HttpSession object is obtained using getSession() on a given request:
HttpSession session = request.getSession();
If a session object doesn't yet exist for the request, the method creates and returns a new session object.You can use the session object as a vehicle for passing data between requests. You use the setAttribute method to bind objects to the session. Likewise, you use getAttribute to retrieve objects from the session. In the AffableBean application for example, the user's shopping cart is created and bound to the user session in the following manner:
ShoppingCart cart = new ShoppingCart();
session.setAttribute("cart", cart);
In order to retrieve the cart from the session, the getAttribute method is applied:
cart = (ShoppingCart) session.getAttribute("cart");
In JSP pages, you can access objects bound to the session using EL expressions. Continuing with the above example, if a ShoppingCart object named 'cart' is bound to the session, you can access the object using the following EL expression:
${cart}



HttpSession main methods [6]:


MethodDescription
Object getAttribute(String key)Returns the object bound with the specified name in this session, or null if no object is bound under the name.NOTE: remember to cast the return value to the appropriate type and check whether the result is null;
void setAttribute(String key, Object value)Binds an object to this session, using the name specified.
void removeAttribute(String key)Removes the object bound with the specified name from this session.
Enumeration getAttributeNames()Returns an Enumeration of String objects containing the names of all the objects bound to this session.
void invalidate()
Invalidates this session and unbinds any objects bound to it.
String getId()Returns a string containing the unique identifier assigned to this session.
boolean isNew()Returns true if the client does not yet know about the session or if the client chooses not to join the session.
long getCreationTime()Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
long getLastAccessedTime()Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
int getMaxInactiveInterval()Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
void setMaxInactiveInterval(int interval)Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Letting Sessions Live Across Browser Restarts
Issue: By default, Java sessions are based on cookies that live in the browser’s memory, but go away when the browser is closed. This is often, but not always, what you want.
Solution: Explicitly send out the JSESSIONID cookie.
 - Do this at the beginning of the user’s actions
 - Call setMaxAge first
Problem:
– Using a cookie with a large maxAge makes no sense
unless the session timeout (inactiveInterval) is also large
– An overly large session timeout can waste server memory

Session Tracking Basics, Sample Code:
HttpSession session = request.getSession();
synchronized (session) {
    SomeClass value =
            (SomeClass) session.getAttribute("someID");
    if (value == null) {
        value = new SomeClass();
    }
    doSomethingWith(value);
    session.setAttribute("someID", value);
}

Performance tip:
 - Don’t do “synchronized(this)”!
 - Use the session or perhaps the value from the session as the label of the synchronized block

Distributed and Persistent Sessions

  • Some servers support distributed Web appsLoad balancing used to send different requests to different machines. Sessions should still work even if different hosts are hit. 
  • On many servers, you must call setAttribute to trigger replicationThis is a tradeoff: session duplication can be expensive, but gives you better load balancing
     
  • Some servers suport persistent sessionsSession data written to disk and reloaded when server is restarted (as long as browser stays open). Very important for web4!Tomcat 5 through 7 support this 
  • To support both, make session data SerializableClasses should implement the java.io.Serializable interfaceThere are no methods in this interface; it is just a flag:
    public class MySessionData implements Serializable
    ...
    }
    Builtin classes like String and ArrayList are already Serializable


Cookies

Basic functionality:Cookies involve name/value pairs sent from server to browser and automatically returned when the same page (or possibly same site or domain) is visited later.

Cookies let you:

  • Track sessions (use higher-level session-tracking API)
  • Permit users to avoid logging in at low-security sites
  • Customize sites for different users
  • Focus content or advertising

Cookie class
Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.
The servlet sends cookies to the browser by using the HttpServletResponse#addCookie method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest#getCookies method. Several cookies might have the same name but different path attributes.  
  • String getName()
    Returns the name of the cookie. There is no setName method: you supply name to constructor. For incoming cookie array, you use getName to find the cookie of interest.
     
  • String getValue()
    Gets the current value of this Cookie.
     
  • getDomain/setDomain
    Lets you specify domain to which cookie applies. Current host must be part of domain specified.
     
  • getMaxAge/setMaxAge
    Gets/sets the cookie expiration time (in seconds). Useful to tell browser to store cookie on disk instead of just in memory (argument is in seconds). If you fail to set this, cookie applies to current browsing session only.
    After setting it use response.addCookie: if you forget this step, no cookie is sent to the browser!

    Session cookies: If no maxAge is specified the default value is "-1": this means the cookie will be active for the current section only (when the browser is closed the cookie is destroyed);
    Persist session cookies: If you do specify a maxAge with a value >0 then the cookie will be persisted on the client for the specified time lenght (this survives closing the browser and will not be destoyed till the maxAge time is reached);
    Tell the browser to delete a cookie:  Call setMaxAge(0)
     
  • getPath/setPath
    Gets/sets the path to which cookie applies. If unspecified, cookie applies to URLs that are within or below directory containing current page.
     
  • getSecure/setSecure
    Gets/sets flag indicating whether cookie should apply only to SSL connections or to all connections.
     
  • getValue/setValue
    Gets/sets value associated with cookie. For new cookies, you supply value to constructor, not to setValue. For incoming cookie array, you use getName to find the cookie of interest, then call getValue on the result. If you set the value of an incoming cookie, you still have to send it back out with response.addCookie.
  Other:
  • response.addCookie(c);
    Place the Cookie into the HTTP response, if you forget this step, no cookie is sent to the browser!
     
  • request.getCookies()
    This yields an array of Cookie objects


Examples of usage:
Sending cookies to the client[5]:
  • Create a Cookie object.
    Call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
    Cookie c = new Cookie("userID", "a1234");
     
  • Set the maximum age.
    To tell browser to store cookie on disk instead of just in memory, use setMaxAge (argument is in seconds)
    c.setMaxAge(60*60*24*7); // One week
     
  • Place the Cookie into the HTTP response
    Use response.addCookie.
    If you forget this step, no cookie is sent to the browser!
    response.addCookie(c);
Reading cookies from the client[5]:
  • Reading Cookies from the Client
    Call request.getCookies
    This yields an array of Cookie objects.
     
  • Loop down the array, calling getName on each entry until you find the cookie of interest
    Use the value (cookie.getValue()) in application-specific way.
     
  • Example:
    String cookieName = "userID";
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for(Cookie cookie: cookies) {
            if (cookieName.equals(cookie.getName())) {
                doSomethingWith(cookie.getValue());
            }
        }
    }

Redirecting or Forwarding to a new page [7]

Theres 2 alternatives to go from a servlet to a new page:

  • using RequestDispatcher.forward
  • or using response.sendRedirect
NOTE: none of them stops processing after being invoked!
A way to stop is invoking "return" to terminate servlet processing.

RequestDispatcher.forward
Ex.:
RequestDispatcher dispatcher =
    request.getRequestDispatcher
    ("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
return;//stop any further processing on the servlet

response.sendRedirect
Ex.
response.sendRedirect("somePage.jsp");
return;//stop any further processing on the servlet

RequestDispatcher.forward VS response.sendRedirect 
In MVC programming with servlets+jsp, RequestDispatcher.forward is the preferred way to do it.

Distinctions:
RequestDispatcher.forward response.sendRedirect
User sees only the first url (servlet URL) User sees new url (JSP URL)
Only one round trip to client; Two round trips to client;
User cannot bookmark second page (JSP page) User can bookmark page (User can visit JSP page separately);
BUT: Since user can visit JSP page without going through servlet first, bean data might not be available (so, JSP page needs code to detect this situation)


References

[1] - The NetBeans E-commerce Tutorial - Adding Entity Classes and Session Beans
[2] - The NetBeans E-commerce Tutorial - Managing Sessions
[3] - The NetBeans E-commerce Tutorial - Connecting the Application to the Database
[4] - Generating the Server Response: HTTP Response Headers
[5] - Handling Cookies
[6] - Session tracking
[7] - The Model View Controller (MVC) Architecture: Integrating Servlets and JSP

Sem comentários:

Enviar um comentário