Thursday, April 28, 2011

Chapter 46: JSP API

This chapter is going to be a quick-review guide or an API for the Java Server Pages (JSP) Technology. A point to note is that, you can find all these details in the Sun Specification for JSP Technology in their website. The difference is that, this one is a bit concise and covers just the important stuff that you can use to quickly review the JSP Technology Syntax for the SCWCD Certification Exam.

Syntax Rules for JSP

There are a few general syntax rules to keep in mind while coding JSP Pages:
• All tags are case sensitive.
• A pair of single quotes is equivalent to a pair of double quotes. This is generally true in HTML tags as well. Note that single quotes must be matched with single quotes, and doubles with doubles.
• Outside of quotes, spaces don't count, but inside they do. Also, spaces are not allowed between an equals sign and an attribute value. This is consistent with current XML/HTML tagging practices in that spaces are supposed to be used only to separate attribute-value pairs from each other and from the name of the tag.
• JSP tags and their XML equivalents cannot be mixed (well) within a page. You don't throw JSP inside an XML tag. Likewise, you must be very careful if you try to use an XML tag inside, say, a scriptlet. The following is wrong:
< % customerCount=8; < myTagLibrary:customer count="8" >
System.out.print(customerCount); % >
A page in one syntax can include or forward to a page in the other syntax.

HTML or Output Comment

These are plain HTML comments that are passed through to the client. The client doesn't process these. There is nothing special about them and the servlet container ignores them, passing them through as text. Notice how you can use a scriptlet to insert text in the comment before it is sent off to the client. For example, you can datestamp a comment.

JSP Syntax

< ! - - comment [ < % = expression % > ] - - >

XML Syntax

None.

Example

< % @ page language="java" % >
< html >
< head >
< title >Hidden Comment< / title >
< / head >
< body >
< h1 >Hidden Comment< / h1 >
< ! - - Any text between these delimiters is passed through by the processor and is included in the response including this: < % = "scriplet" % >.
- - >
< / body >
< / html >

Which produces

< html >
< head >
< title >Hidden Comment< / title >
< / head >
< body >
< h1 >Hidden Comment< / h1 >
< ! - - Any text between these delimiters is passed through by the processor and is included in the response including this: scriplet. - - >
< / body >
< / html >

Hidden Comment

The text within a hidden comment (< % - - - - % >) is ignored by the JSP container. Unlike HTML comments, within which you can embed scriptlets, you don't place scriptlets in a hidden comment. The JSP container does not process anything between the < % - - and - - % > characters. A hidden comment is not inserted into the response.

JSP Syntax

< % - - comment - - % >

XML Syntax

None.

Example

< % @ page language="java" % >
< html >
< head >
< title >Hidden Comment< / title >
< / head >
< body >
< h1 >Hidden Comment< / h1 >
< % - - Any text between these delimiters is ignored by the processor and is not included in the response - - % >
< / body >
< / html >

Declaration

A declaration declares variables or methods that you can use afterward in the JSP page. The declaration must precede these variables' use in the JSP page. You can place numerous declarations between the delimiters. The following rules apply:
• Terminate the declaration with a semicolon. This is the same for scriptlets, but the opposite of an Expression.
• You don't have to declare variables or methods that are already declared in imported packages.
• Since a static include file is treated as original JSP source, declarations in these must precede use. Conversely, declared variables are accessible from include files if the include directive comes after the declaration. The scope of a declaration does not include dynamic resources included with < jsp : include >

JSP Syntax

< % ! declaration; [ declaration; ]+ ... % >

XML Syntax

< jsp : declaration >
declaration; [ declaration; ]+ ...
< / jsp : declaration >

Example

< % ! String firstName = new String("Patricia"); % >
< % ! int customerCount = 84; % >

Expression

A JSP expression can be any valid Java expression. The container evaluates it, converts the result to a String, and appends this String to the output stream. The only surprise with this element is you do not use a semicolon to terminate the statement. If you remove the equals sign from the opening delimiter, you have a scriptlet and must use a semicolon even though it is the same Java expression.

JSP Syntax

< % = expression % >

XML Syntax

< jsp : expression >
expression
< / jsp:expression >

Example

< % @ page language="java" % >
< html >
< head >
< title >Hidden Comment< / title >
< / head >
< body >
< h1 >Expression < / h1 >
< % = "This expression is simply a String." % >
< / body >
< / html >

Scriptlet

This contains a code fragment, containing valid Java statements and/or local variable declarations. These statements and declarations will be placed in a method (the _jspService method) when the JSP gets converted to a Servlet

JSP Syntax

< % code fragment % >

XML Syntax

< jsp : scriptlet >
code fragment
< / jsp : scriptlet >

Example

< jsp : directive.page import="java.util.Date" / >
< jsp : scriptle t >
Date date = new Date();
String message = getDate(date);
< / jsp : scriptlet >
< jsp : text >
< html >
< head >
< title >Expression in XML Syntax< / title >
< / head >
< body >
< h1 align="center" >
< jsp : expression > message < / jsp : expression >
< / h1 >
< / body >
< / html >
< / jsp : text >
< jsp : declaration >
String getDate(Date date)
{
String message = "The date is: " + date;
return message;
}
< / jsp : declaration >


Which produces this

< html >
< head >
< title >Expression in XML Syntax< / title >
< / head >
< body >
< h 1 align="center" >
The date is: Fri Apr 29 09:47:22 IST 2011
< / h1 >
< / body >
< / html >

Include Directive

An include directive inserts all the text in the named file into the JSP page at the point of the tag. Notice that it is as if this text is part of the JSP, so it is processed along with the rest of the JSP. This is called a static process. In other words, the container copies the text referenced in the file and does not process it in any way before being inserted into the JSP page. The included file can be any text, including pieces of JSP, HTML, XML, or plain text. Once this text is included, it is parsed as if it had been in the original JSP page.
Notice how this static include compares to the HTML equivalent: < ! - - #include file="somefile.html" - - >. This HTML include is performed by the browser, which also inserts the result of this fetch into the HTML page. However, in the HTML include case, the referenced resource can be static (HTML, stylesheet) or dynamic (like a servlet or JSP page). If it is dynamic then whatever that resource sends back is what is placed inline at the point of the include tag.

JSP Syntax

< % @ include file="relativeURL" % >

XML Syntax

< jsp : directive.include file="relativeURL" / >

Example

< jsp : text >
< html >
< head >
< title >Example Include< / title >
< / head >
< body >
< h1 align="center" >
< jsp : directive.include file="message.txt" / >
< / h1 >
< / body >
< / html >
< / jsp:text >

message.txt contains

This text was included from another file.

The output is

< html >
< head >
< title >Example Include< / title >
< / head >
< body >
< h1 align="center" >This text was included from another file.
< / h1 >
< / body >
< / html >

Page Directive

This tag is the most powerful one of the bunch. It defines attributes that apply to an entire JSP page.

Notice that you can use the page directive more than once. However, you can only use each attribute once. Imports are the only exception. Also, you can place it anywhere on the page. I strongly recommend grouping these tags together, normally at the top or bottom of the file.

JSP Syntax

< % @ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*},..." ] [ session="true|false" ] [ buffer="none|8kb|sizekb" ] [ autoFlush="true|false" ] [ isThreadSafe="true|false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="mimeType [ ; charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ] [ isErrorPage="true|false" ] [ pageEncoding="characterSet | ISO-8859-1" ] % >

XML Syntax

< jsp : directive.page pageDirectiveAttrList / >

Example

< % @ page import="java.util.*" % >

Or

< jsp : directive.page language="java" / >

Taglib Directive

The taglib directive tells the container that you will use custom tags. It names the tag library and specifies their tag prefix. You can use many taglib directives in a single page, but the prefix defined in each must be unique.

JSP Syntax

< % @ taglib uri="URIForLibrary" prefix="tagPrefix" % >

XML Syntax

No direct equivalent, but you can specify a tag library in < jsp : root > .

Example

< % @ taglib uri="/que_taglib_message" prefix="message" % >
< % @ page language="java" % >
< html >
< head >
< title >Tag Library< /title >
< /head >
< body >
< h1 >Tag Library< /h1 >
< message:insert definition="appendix" parameter="syntax"/ >
< /body >
< /html >

< jsp:text >

A jsp:text element allows you to add text that you want sent to the client unaltered within the XML tags. The text you place in here is appended literally to the output stream.

JSP Syntax

None. There is no direct syntax. Anything that is not JSP syntax is “text.”

XML Syntax

< jsp:text >
your text
< /jsp:text >

Example

< jsp:text >
< html >
< head >
< title >jsp:text Example< /title >
< /head >
< body >
< h1 align="center" >
This is a jsp:text example.
< /h1 >
< /body >
< /html >
< /jsp:text >

< jsp:include >

The < jsp:include > element allows you to include text in a JSP page. There are two kinds. One is static (text is simply inserted as if it were part of the original JSP page) and the other is dynamic (text is processed first and then only the result is inserted into the JSP page). If it is dynamic, you can use a < jsp:param > clause to pass the name and value of a parameter to the resource.

JSP Syntax

< jsp:include page="{relativeURL | < % = expression % >}"
flush="true|false" / >

Or

< jsp:include page="{relativeURL | < % = expression % >}"
flush="true|false" >
< jsp:param name="parameterName" value="{parameterValue | < % = expression % >}" / >+
< /jsp:include >

XML Syntax

< jsp:include page="{relativeURL | % = expression % }" [ flush="true | false" ] / >

Or

< jsp:include page="{relativeURL | % = expression % }" [ flush="true | false" ] >
[ < jsp:param name="parameterName" value="{parameterValue | % = expression % }" / > ] +
< /jsp:include > }

Example

< jsp:include page="company_logo.html" / >
< jsp:include page="salesTax.jsp" >
< jsp:param name="state" value="CA" / >
< jsp:param name="amount" value="359.92" / >
< /jsp:include >

< jsp:plugin >

This tag tells the browser to load an applet or bean. You have to specify both the applet/bean and the plug-in. If the client can't find the plug-in, the browser should display a dialog to initiate the download of the plug-in software.

JSP Syntax

< jsp:plugin type="bean|applet" code="classFileName" codebase="classFileDirectoryName" [ name="instanceName" ] [ archive="URIToArchive, ..." ] [ align="bottom|top|middle|left|right" ] [ height="{displayPixels | < % = expression % >}"]
[ width="{displayPixels | < % = expression % >}"]
[ hspace="leftRightPixels" ]
[ vspace="topBottomPixels" ]
[ jreversion="JREVersionNumber | 1.2" ]
[ nspluginurl="URLToPlugin" ]
[ iepluginurl="URLToPlugin" ] >
[ < jsp:params >
[ < jsp:param name="parameterName" value="{parameterValue | < % = expression % >}" / > ]+
< /jsp:params > ]
[ < jsp:fallback > text message if plugin download fails
< /jsp:fallback > ]
< /jsp:plugin >

XML Syntax

< jsp:plugin type="bean|applet" code="classFileName" codebase="classFileDirectoryName" [ name="instanceName" ] [ archive="URIToArchive, ..." ] [ align="bottom|top|middle|left|right" ] [ height="{displayPixels | % = expression % }" ] [ width="{displayPixels | % = expression % }"] [ hspace="leftRightPixels" ] [ vspace="topBottomPixels"] [ jreversion="JREVersionNumber | 1.2" ] [ nspluginurl="URLToPlugin" ] [ iepluginurl="URLToPlugin" ] >
[ < jsp:params >
[ < jsp:param name="parameterName" value="{parameterValue | % = expression % }" / > ]+
< /jsp:params > ]
[ < jsp:fallback > text message if plugin
download fails
< /jsp:fallback > ]
< /jsp:plugin >

Example

< jsp:plugin type=applet code="houseViewer.class" codebase="/html" >
< jsp:params >
< jsp:param name="property_listing" value="A33IN" / >
< /jsp:params >
< jsp:fallback >
< p >Unable to load applet< /p >
< /jsp:fallback >
< /jsp:plugin >

< jsp:useBean >

The < jsp:useBean > element locates or instantiates a JavaBeans component. If it does not exist, the container will attempt to instantiate it from a class or serialized template. You can access a JavaBeans component, but not an enterprise bean directly. However, you can call a JavaBean that in turn calls an EJB.

JSP Syntax

< jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class" [ type="package.class" ]| beanName="{package.class | < % = expression % >}"
type="package.class" |
type="package.class"
}
{ / > | > other elements < /jsp:useBean > }

XML Syntax

< jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class" [ type="package.class" ] | beanName="{package.class | % = expression % }" type="package.class" | type="package.class" } { / > | > other elements < /jsp:useBean > }

Example

< jsp:useBean id="houseLotBean" scope="session" class="session.Realestate" / >
< jsp:setProperty name="houseLotBean" property="id" value="33245" / >

< jsp:setProperty >

This element sets the value of one or more properties in a bean, using the bean's setter methods. Of course, the < jsp:useBean > tag must be declared first. The most frequent mistake with this tag is to not match the value of name in < jsp:setProperty > with the value of id in < jsp:useBean >.

JSP Syntax

< jsp:setProperty name="beanInstanceName" { property="*" | property="propertyName" [ param="parameterName" ] | property="propertyName" value="{stringLiteral| < % = expression % >}"
}
/ >

XML Syntax

< jsp:setProperty name="beanInstanceName" { property="*" | property="propertyName" [ param="parameterName" ] | property="propertyName" value="{stringLiteral | % = expression % }" } / >

Example

< jsp:setProperty name="houseLotBean" property="id" value="33245" / >

Another example that takes the values of all form fields coming in from a form and assigns them to bean properties that have the same names as these form fields:
< jsp:setProperty name="request" property="*" / >

< jsp:forward >

This element forwards the request object (which has all client request information) from one JSP page to another resource. The target can be an HTML file, another JSP page, or a servlet, as long as it is in the same application context as the forwarding JSP page. Notice how the lines in the source JSP page after the < jsp:forward > element are not processed.
The biggest problem you'll have with this one is trying to forward after some output has been sent to the client. This happens if you are not buffering output (page directive buffer=”none”). If you forward in this situation you will cause an IllegalStateException.

JSP Syntax

< jsp:forward page="{relativeURL | < % = expression % >}" / >

or

< jsp:forward page="{relativeURL | < % = expression % >}" >
< jsp:param name="parameterName" value="{parameterValue | < % = expression % >}" / > +
< /jsp:forward >

XML Syntax

< jsp:forward page="{relativeURL | % = expression % }" >
< jsp:param name="parameterName" value="{parameterValue | % = expression % }" / > +
< /jsp:forward > }

Example

< jsp:forward page="page_moved_page.htm" / >

< jsp:getProperty >

This tag is how you retrieve a value from a bean using its getter method.

JSP Syntax

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

XML Syntax

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

Example

< jsp:useBean id="tax" scope="page" class="state.Tax" / >

Current tax rate is:< jsp:getProperty name="tax" property="taxRate" / >

Previous Chapter: Self Test - chapters

Next Chapter: Chapter 47 - Introduction to Web Application Deployment

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers