JSP CHEAT SHEETS

JSP Quick Reference Card & JSP Developer Cheat Sheet

JSP Quick Reference: This page combines the two supplied JSP reference documents into the same responsive HTML learning format used for the previous cheat sheets. The first document covers JSP syntax, directives, scripting elements, actions and implicit objects; the second covers JSP fundamentals, forms, sessions, cookies and JDBC.

JSP Quick Reference Card

Default Scripting Language

The scripting language of a JSP page defaults to Java.

To configure the page to use JavaScript:

<%@ page language = "javascript" %>

Using White Space

White space contained within the template code is returned to the client as it was entered in the JSP.

Quoting Attribute Values

Quote attribute values using either single or double quotes for JSP elements.

<%@ page contentType = "text/plain" %>

Writing Comments for the JSP

A JSP comment is not output to the client as part of the JSP page's output.

<%-- Comment string... --%>

Outputting Comments to the Client

HTML comments are output to the client.

<!-- comments -->

JSP Directives

DirectivePurposeSyntax / Example
page Defines page-wide attributes.
<%@ page attribute="value" ... %>
include Inserts text into a JSP page.
<%@ include file = "path" ... %>
taglib Defines a custom tag library used by a JSP page.
<%@ taglib uri="tagLibraryURI"
prefix="tagPrefix" %>

Page Directive Attributes

AttributeDefault / Description
languagejava
sessiontrue
contentTypetext/html;charset="ISO-8859-1"
importpackage(s)
buffer8kb
autoflushtrue
isThreadSafetrue
infotext_string
errorPagerelativeURL
isErrorpagetrue
extendsclass_name

The value is a string literal in single or double quotes.

Scripting Elements

ElementPurposeSyntax
declaration Creates page-wide definitions such as variables.
<%! declaration %>
scriptlet Contains a block of scripting code. A JSP page can contain multiple blocks of scripting code.
<% script code %>
expression Defines statements evaluated on the server before sending the page output to the client.
<%= expression %>

Declaration Example

<%!
private String foo = null;
public String getFoo() {
    return this.foo;
}
%>

Scriptlet Example

<%
String greeting = request.getParameter("Greeting");
out.println(greeting);
%>

Expression Example

<%= myVar1 %>

JSP Actions

jsp:include

Calls one JSP page from another. Upon completion, the destination page returns control to the calling page.

<jsp:include page="path" flush="true"/>

<jsp:include page="path" flush="true">
    <jsp:param name="paramName"
               value="paramValue" />
</jsp:include>

jsp:forward

Calls one JSP page from another. Execution of the calling page is terminated by the call.

<jsp:forward page="path" />

<jsp:forward page="path">
    <jsp:param name="paramName"
               value="paramValue" />
</jsp:forward>

jsp:plugin

Enables you to invoke an applet on a client browser.

<jsp:plugin
    type="bean|applet"
    code="objectCode"
    codebase="objectCodebase"
    align="alignment"
    archive="archiveList"
    height="height"
    hspace="hspace"
    jreversion="jreversion"
    name="componentName"
    vspace="vspace"
    width="width"
    nspluginurl="url"
    iepluginurl="url">

    <jsp:params>
        <jsp:param name="paramName"
                   value="paramValue" />
    </jsp:params>

    <jsp:fallback>
        arbitrary_text
    </jsp:fallback>

</jsp:plugin>

jsp:useBean

Defines an instance of a Java bean.

<jsp:useBean id="name"
    scope="page|request|session|application"
    typeSpec />

<jsp:useBean id="name"
    scope="page|request|session|application"
    typeSpec>
    body
</jsp:useBean>

typespec:

  • class="className"
  • class="className" type="typeName"
  • beanName="beanName" type="typeName"
  • type="typeName"

jsp:setProperty

Sets the value of one or more properties in a bean.

<jsp:setProperty name="beanName" prop_expr />

prop_expr can be:

  • property="*"
  • property="propertyName"
  • property="propertyName" param="parameterName"
  • property="propertyName" value="propertyValue"

jsp:getProperty

Writes the value of a bean property as a string to the out object.

<jsp:getProperty name="name"
    property="propertyName" />

JSP Built-in / Implicit Objects

ObjectDescriptionJava Type
applicationThe servlet context obtained from the servlet configuration object.javax.servlet.ServletContext
configThe ServletConfig object for the JSP page.javax.servlet.ServletConfig
exceptionThe uncaught exception that resulted in the error page being invoked.java.lang.Throwable
outAn object that writes into a JSP page's output stream.javax.servlet.jsp.JspWriter
pageContextThe page context for the JSP.javax.servlet.jsp.PageContext
requestThe client request.javax.servlet.HttpServletRequest
responseThe response to the client.javax.servlet.HttpServletResponse
sessionThe session object created for the requesting client.javax.servlet.http.HttpSession

JSP Developer Cheat Sheet

J2EE Structure

Layer / ComponentDescription
ClientWeb browser
ServerJSP / JServlet / Tomcat
BackendDatabase
Server ConfigurationEclipse Server config
MVCStruct, Spring, JSF

JSP Fundamentals

ConceptSyntax / Description
jsp expression<%= java statement %>
jsp scriptlet<% anonymous java blocks %>
jsp import<%@ page import= comma separated java import %>
jsp declaration<%! named java blocks, ie methods %>
Call Java class from JSPAvoid large chunks of Java code (scriptlets or declarations) in JSP.
Include<jsp:include file="header.jsp" />

JSP Built-in Objects

ObjectDescription
requestHTTP request header + form data
responseHTTP support for sending response
outJspWriter: include content in HTML
sessionUnique session for each user across different pages
applicationShared among users of web app

Read HTML Form in JSP

<form id="test"
      action="student-response.jsp"
      method="post">

    name:
    <input type="text" name="name"/>

    <input type="radio"
           name="isSophomore"
           value="Yes"> Yes

    <input type="radio"
           name="isSophomore"
           value="No"> No

    <input type="checkbox"
           name="language"
           value="Javascript"> Javascript

    <input type="checkbox"
           name="language"
           value="Java"> Java

    <input type="checkbox"
           name="language"
           value="SQL"> SQL

    <input type="checkbox"
           name="language"
           value="python"> Python

    <input type="submit" value="Submit"/>
</form>

<select name="country" form="test">
    <option value="China">China</option>
    <option value="US">US</option>
    <option value="Other">Other</option>
</select>

Reading Form Parameters in JSP

${param.name}
${param.country}

<%=request.getParameter("country")%>

Reading Multiple Checkbox Values

<ul>
<%
String[] language =
    request.getParameterValues("language");

if (language != null)
    for (String s : language)
        out.println("<li>" + s + "</li>");
%>
</ul>

Session

A session is unique for a user and can share data across pages, such as a shopping cart for a user. It is kept in memory and each user has a session ID. The browser handles the session ID.

OperationExample
Set attributesession.setAttribute("name", value)
Get attribute(List<String>) session.getAttribute("name")
Check new sessionsession.isNew()
Get session IDsession.getId()
Invalidate sessionsession.invalidate()
Set timeoutsession.setMaxInactiveInterval(ms)

Typical flow:

  1. Create form
  2. Check and set session attribute
  3. Read from session

To disable session:

<%@ page session="false" %>

PageContext

The reference also lists PageContext in the session section.

Cookies & Session

Cookie API

Cookie API is in javax.servlet.http and is imported implicitly for JSP pages.

Cookie(String name, String value);

Cookie theCookie =
    new Cookie("myApp.favoriteLang", favLang);

theCookie.setMaxAge(606024*365);

// default 30min
response.addCookie(theCookie);

Cookie[] theCookies = request.getCookies();

if (theCookies != null) {
    for (Cookie tempCookie : theCookies) {
        // process cookie
    }
}

Cookie Characteristics

  • Only sent to the specific server when the domain matches.
  • A cookie is data stored by the browser and sent to the server with every request.
  • Cookies with no expiration time can be deleted after the browser is closed, depending on browser behavior.

Cookie vs Session

CookieSession
Data stored by the browser and sent with requests. Collection of data stored on the server and associated with a user.
Usually associated with a domain. Usually associated with a session ID, often carried using a cookie.
Can have an expiration time. Can expire based on session inactivity or invalidation.

Reading Cookies

<%
Cookie[] theCookies = request.getCookies();

if (theCookies != null) {
    for (Cookie tempCookie : theCookies) {

        if ("myApp.favoriteLang"
                .equals(tempCookie.getName())) {

            favLang = tempCookie.getValue();
            break;
        }
    }
}
%>

JDBC & Connection Pool

Setup Notes from the Reference

  • Install MySQL, Workbench, Shell and demo data setup.
  • Set up Tomcat 7.0 by downloading Tomcat 7 and unzipping it to c:\.
  • Set up a connection pool for multiple users sharing the same database.
  • The pool saves resources by avoiding a new connection setup every time.
  • Download the MySQL JDBC connector JAR and place it under WebContent/WEB-INF/lib.
  • Define the connection pool in WebContent/META-INF/context.xml.

Tomcat DataSource Configuration

<Context>

    <Resource
        name="jdbc/web_student_tracker"
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="20"
        maxIdle="5"
        maxWait="10000"
        username="webstudent"
        password="webstudent"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/web_student_tracker?useSSL=false"
    />

</Context>

Resource Injection

Tomcat automatically sets the connection pool / datasource on the servlet, according to the supplied reference.

Connector / MySQL Note

-- connector/J 8

alter user 'webstudent'@'localhost'
identified with mysql_native_password
by 'webstudent';

Cache Busting

The second supplied cheat sheet contains a cache-busting reference.

https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/
Source note: The HTML preserves the terminology, examples and organization contained in the supplied JSP reference documents. The first document is a two-page “JSP Quick Reference Card” containing directives, scripting elements, actions and JSP objects. fileciteturn2file0L2-L7 The second document contains JSP fundamentals, form handling, sessions, cookies and JDBC setup notes. fileciteturn2file1L4-L10