My JSP
<%-- JSP comments are stripped when converting JSP to servlet --%>
<%-- Servlet generated by JSP in
\work\Catalina\localhost\\org\apache\jsp> --%>
<%-- bad practice to have Java scriptlets in JSP use EL and actions instead --%>
<%-- JSP element types
directive (e.g <%@ page ... %>
declaration (e.g <%! int x; %>
EL expression ( ${..} )
scriptlet ( <% ++x; %> )
expression ( <%= x %> )
action ( )
--%>
<%-- 3 directives --%>
<%@ page import="java.util.*, java.io.*" isELIgnored="false"%>
<%--
<%@ taglib tagdir="/WEB-INF/tags/cool" prefix=cool %> tagdir or uri
<%@ include file="foo.html"%>
--%>
<%-- page directive has 13 attributes
import
isThreadSafe="false" use SingelThreadModel
contentType (cannot do contentType="<%getVal()%>")
isELIgnored (disable Expression Language scripting)
isErrorPage (if true has access to exception object)
errorPage (URL to send for uncaught Throwable)
session (wether page participates in session)
language="java", extends, buffer, autoFlush, info, pageEncoding
--%>
<%-- java.servlet.jsp.JspPage methods jspInit() and jspDestory() --%>
<%-- put code starting with tag outside of service method --%>
<%!
// any method or variable declaration can go here
public void foo() {}
public void jspInit() {
// implicit objects not available here
System.out.println("*** my.jsp " + getServletConfig().getInitParameter("servletparam"));
getServletContext().setAttribute("email", "s_desai@hotmail.com");
} %>
<%! public void jspDestroy() {} %>
<%-- cannot override javax.servlet.jsp.HttpJspPage._jspService() --%>
<%-- instance variable --%>
<%! int x=1; %>
<%--
JSP attribute scopes -> application, config, request, session, page
page (page scope for request only)
implicit objects avialable only in service() i.e <% %> or <%= %>
JspWriter out (extends Writer not PrintWriter)
HttpServletRequest request
HttpServletResponse response
HttpSession session
ServletContext application
ServletConfig config
Throwable exception (avaiable only for error pages)
PageContext pageContext (adds new page scope)
Object page ( page=this )
--%>
<%-- You can use pageContext to fetch attribute for any scope
JspContext
getAttribute(String name) geAttribute(String name, int scope)
getAttributeNamesInScope(int scope)
findAttribute(String) // find in page, request, session, application
PageContext extends JspContext
APPLICATION_SCOPE, PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE
getRequest() getServletConfig() getServletContext() getSession()
--%>
<%-- code below goes in JSP Service method --%>
<% Object val = application.getAttribute("foo"); %>
<% val = pageContext.getAttribute("foo", PageContext.APPLICATION_SCOPE); %>
<%-- find first in page, request, session, application --%>
<% val = pageContext.findAttribute("foo"); %>
<%-- next two lines are same --%>
<%-- scriptlet --%>
<% out.println(new Date()); %>
<%= new Date() %> <%-- expression goes in out.prinltn no ; --%>
apple
<%-- variable declared inside service method --%>
<% int x=1;%>
<%-- Expression Language better alternative to scriptlets --%>
My email is : ${applicationScope.email}
${'${'}text} <%-- escape ${ output is ${text} --%>
<%-- actions --%>
<%-- useBean will create bean if required scope defaults to page
scope can be application, session, request, page
note config is invalid value
--%>
<%-- this code invoked only if new bean created --%>
Employee name is: ${emp.name}
Employee ID is: ${emp.empID}
<%-- use type to create polymorphic beans
foo.PersonBean = (foo.PersonBean) findAttribute("person");
if we use type without class then bean should exist
else InstantiationException that bean not found
Note class cannot be abstract, type can be anything i.e interface, abstract class
type is reference, class is instantiation
note setProperty will convert String to int if required
beanName and class cannot be used together, will use Beans.instantiate() to create object
--%>
<%-- this code invoked only if new bean created --%>
Person name is: ${person.name}
Person name is: ${person["name"]}
<%-- same as above --%>
<%-- **************
EL is in ${firstThing.secondThing}
firstThing is either implicit object or attribute
secondThing should follow Java variable naming rules so ${foo.1} invalid
EL implicit objects (all are Map except for pageContext)
pageScope, requestScope, sessionScope, applicationScope (they are not request, session etc objects)
param, paramValues (Maps of request parameters)
header, headerValues
cookie
initParam
pageContext (not Map) (use to access session, request, response, servletContext)
EL cannot have assignment
EL does not throw errors on null or if attribute not found
{$zzz["aaa"} will print nothing as zzz attribute does not exist
null in boolean is false
null in arithmetic is zero
****************** --%>
<%-- cannot do ${requestScope.method} --%>
HTTP method is ${pageContext.request.method}
toppings using param and paramValues
First topping ${param.toppings}
Second topping ${paramValues.toppings[1]}
<%-- param is get value by doing request.getParameter("empName") --%>
<%-- if no param and value specified will do request.getParameter() on property name --%>
<%-- This will not convert String to int
"/>
--%>
You entered in form: ${empform.name}
<%-- The form parameter names in HTML should match the Bean property names --%>
Your empid is ${param.empID}
<%-- using implicit param object --%>
Your name is ${empform2.name} empID is ${empform2.empID}
<%-- accessing nested property --%>
Your car is ${empform2.car.make}
<%--
The . operator used for accessing property
. operator cannot access map key only bean property
[] operator for accessing bean, list, array, Map
${firstThing[secondThing]}
firstThing can be attribute that returns java.util.Map, java.util.List,
array or bean or it can be bean
secondThing can be key or index
${foo.bar+1} will not work
HashMap foo;
request.setAttribute("bar", "a");
${foo['bar']} look for bar key value
${foo[bar]} find value of bar attribute first
${foo[requestScope['bar']]} look for bar attribute
--%>
<%
HashMap f1 = new HashMap(); f1.put("a", "1"); f1.put("b", "2");
request.setAttribute("lettersMap", f1);
request.setAttribute("zz.lettersMap", f1);
String[] f2 = {"a", "b"};
request.setAttribute("lettersArray", f2);
%>
The value of a is ${lettersMap["a"]}
Nested value ${lettersArray[lettersMap["a"]]}
<%-- we need to use [] because zz.lettersMap["a"] would fail --%>
The value of a is ${requestScope["zz.lettersMap"]["a"]}
<%
Cookie cookie = new Cookie("user", "foo");
response.addCookie(cookie);
%>
Cookie user has value: ${cookie.user.value}
DD appName value is ${initParam.appParam}
<%-- ${empty null} true
return true if object is null or string, array, collection, Map empty
else false
${empty 0} is false
--%>
<%-- Calling static methods see company.tld and EmployeeTagHandler for details
comapny.tld can be located in any directory under WEB-INF
When container loads tld, it creates a map of the uri in the tld
and the location of tld file
TLDs can be in the following locations
WEB-INF directory or subdirectory
WEB-INF/lib/*.jar in the META-INF directory or subdirectory
jspx, java, javax, servlet, sun, sunw prefix cannot be used
exceptions wrapped in ELException
use full path in URI from WEB-INF if TLD not in DD (old style?)
uri="/WEB-INF/tlds/foo.tld"
--%>
<%@ taglib prefix="my" uri="Company" %>
My company is ${my:companyName()}
Calling custom tag title
<%-- 3 ways to call Custom Tag that cannot have body --%>
<%-- empty tag --%>
<%-- does not work tomcat bug
-- empty body
-- with jsp:attribute in body
--%>
<%-- EL operators
+ - * / div % mod ( / by zero no exception, % divide by zero exception)
&& and || or ! not == eq != ne
< lt > gt <= le >= ge
EL does not throw exception for null or unknown value
For arithmetic null is 0 for boolean false
operator precedence (top to bottom, left to right)
[] .
()
- (unary) !
* / %
+ -
< > >= <=
== !=
&&
||
? :
--%>
The value of 3/0 is ${3/0} <%-- Infinity --%>
The value of 4/2 is ${4/2} <%-- 2.0 --%>
<%-- ${4 * (1 ne 2)} compilation error --%>
Is equals ${3 eq "3"} <%-- true --%>
Is equals ${3 eq '3'} <%-- true --%>
Is equals ${blah.blah or true} <%-- true --%>
Is equals ${blah.blah eq false} <%-- null eq false is false --%>
<%-- will include at translation time equivalent to copy and paste here
only directive that is location sensitive --%>
<%@ include file="fooinc.jsp"%>
<%-- will include at compile time should generate two servlets
include at runtime
cannot set header, cookies, cannot change status code
optional atribute flush="true" or "false"
optional flush parameter
--%>
include with parameters
<%-- param is optional --%>
<%-- forward clears the buffer then does forward, so all the above not displayed
if flush done before forward then IllegalStateException
--%>
<% if ("forward".equals(request.getParameter("name"))) { %>
<% } %>
<%--
Copy jstl.jar and standard.jar to WEB-INF\classes directory
c is standard prefix for core JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- not c:else available use c:choose --%>
Hello Sam! c:if is true
<% String[] hondaCars = {"Honda Accord", "Honda Civic"};
String[] toyotaCars = {"Toyota Camry", "Toyota Corolla", "Toyota Prius"};
ArrayList cars = new ArrayList();
cars.add(hondaCars); cars.add(toyotaCars);
request.setAttribute("hondaCars", hondaCars);
request.setAttribute("cars", cars);
%>
<%--
works over array, iterator, enumeration, map, collection, string (, delimiter)
optional-> begin="5" end="3" step="-1" --%>
${car} ,
<%--
varStatus is optional has loop index value
varStatus properties index, count, current, isFirst(), isLast()
--%>
print cars using forEach: and varStatus
${loopStatus.count}:${car},
<%-- tr is table row and td is table data --%>
Nested forEach output
<%-- mutually exclusiv conditions
equivalent to if () {} else if () {} --%>
Output of c:choose
You must be the CEO
You must be the CFO
You are a regular employee
<%-- c:set
var sets attribute
creates attribute if it does not exist
if value null it removes Attribute (i.e value="" will delete)
target sets for attributes with beans/maps only
if target is null exception thrown
if target not map or bean exception thrown
if target is bean and property not found exception thrown
Cannot have both var or target
scope is optional and default is page
--%>
The value after c:set is ${requestScope.fooattrib}
The value after c:set is ${fooattrib}
barSession1,barSession2
The value after c::set with body is ${sessionScope.fooattrib}
<%
foo.EmployeeBean empBean = new foo.EmployeeBean();
request.setAttribute("emp", empBean); %>
The c:set target empID is <%=empBean.getEmpID()%>
The value using c:set target on hashmap of a is ${lettersMap.a}
${emp.empID} <%-- body can be string or expression --%>
The value using c:set target using body on hashmap of a is ${lettersMap.a}
<%-- call removeAttribute --%>
<%-- default if none, escapeXML to escape < & etc --%>
Value from c:out
<%-- Can import page outside of web container, should not contain
optional store to var or varReader
--%>
Do c:import with c:param
<%-- use c:url as substitute for encodeURL
URL rewrite only for relative paths
--%>
Link to fooinc.jsp
<%-- c:param will correctly encode space and reserved characters
passing with ? in c:url will not work for parameters and values with space
String s = "a b"; setAttribute("param1", s);
e.g value='fooinc.jsp?param1=${param1}'
--%>
Link with param to fooinc.jsp
<%-- can specify this in DD with tag
<%@ page errorPage="errorPage.jsp" %>
--%>
dividing by zero
<%-- uncommenting this will send code to errorPage.jsp
<%int z=1/0;%> --%>
<%-- var optional --%>
<% int zz = 1/0; %>
You can't see this
The c:catch exception is ${myException}
<%-- StringTokenizer functionality --%>
<% String s = "a,b;d,e;f";
pageContext.setAttribute("s", s);
%>
${token}
<%-- JSTL 1.1 tags
Core Library
General Purpose
Conditional
URL related
Iteration
Formatting
Internationalization
Formatting
SQL Library
XML Library
XML flow control
Transform actions
--%>
<%--
Custom Tags
Tag Files (Implemented in .tag file) (TLD file required only if tag file in jar file)
Tag Handler (handler implement in java)
implement using SimpleTagSupport
implement using Classic Tags (old style)
--%>
<%-- Calling custom tag (Tag Files) --%>
<%@ taglib prefix="mytags" tagdir="/WEB-INF/tags" %>
<%-- look for mycustom.tag or mycustom.tagx
tag file can be in
WEB-INF/tags directory or subdirectory
META-INF/tags directory or subdirectory in WEB-INF/lib/*.jar
if tag file deploy to a jar it must have a tld file
The tld file only declares location
--%>
<%-- No scripts allowed in body content --%>
Makers of luxury cars
Use Simple Tag by calling foo.MySimpleTag.java
<%@ taglib prefix="mySimple" uri="simpleTags" %>
Passing body to MySimpleTag ${3+2}
<%-- fooAttrib defined in MySimpleTag.java, also see mysimple.tld --%>
Passing body to MySimpleTag: ${fooAttrib}
List of cars, body below gets called multiple times from MySimpleTag.doTag()
${car}
<% ArrayList luxuryCars = new ArrayList();
luxuryCars.add("Lexus RX300"); luxuryCars.add("BMW X5");
request.setAttribute("luxuryCars", luxuryCars);
%>
List of cars, passing list to MySimpleTag
${car}
<%-- uncomment this to test SkipPageException
List of cars, passing incorrect value
This will not be printed
This too will not be printed --%>
<%-- Classic tags not working properly --%>
Calling MyClassic tag handler
<%@ taglib prefix="myClassic" uri="myclassic" %>
Classic with body
Print list of cars using classic tags
${car}