Tag Archives: JSP

Setting Cookies


An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, addresses, passwords, and credit card numbers. To set a cookie in a JSP, the following code is used:

Set-Cookie: cookie-value; expires=date; path=path; domain=domain-name; secure


Getting the Request header


The Request Header contains all kinds of useful data, like the requesters method (GET or POST) but also the requester’s browser an OS. This example shows how to get it;

The request method is <%= request.getMethod() %>
The request URI is <%= request.getRequestURI() %>
The request protocol is <%= request.getProtocol() %>
The browser is <%= request.getHeader("user-agent") %>


Testing a request parameter in a JSP


In JSP’s you need to be careful with request params since they can cause errors. This example shows how to prevent nullpointer exceptions:

<%@ page Page="page.jsp" %>

    if (request.getParameter("param").equals("value")) {
        // ...

    // The test above will throw a
    // NullPointerException if param is
    // not part of the query string. A better
    // implementation would be:
  ("value".equals(request.getParameter("param"))) {
        // ...


Including a jsp fragment in a jsp


This is useful if you need to include a header or footer and you already have them as separate jsp files.

<%@ include file="relativeFragment.jsp" %>


The if statement in a JSP WITH JSTL


The JavaServer Pages Standard Tag Library (JSTL) allows you to use functional tags which simplify  programming in JSP’s. This example shows how it’s done with a simple test for a condition

<%-- Declare the core library --%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>

<%-- Simple  conditions --%>
<c: test='${param.p == "someValue"}'>
    Generate this template text  p equals someValue

<c: test='${param.p}'>
    Generate this template text  p equals "true"