JSP- A quick and dirty introduction
JSP is a means of placing Java code within HTML files to assist in the creation of dynamic websites.
When called for the first time, the Container converts the JSP file into JAVA code, compiles the JAVA code into a Java servlet class, and loads and initializes the servlet in the usual way.
JSP coding consists of the following four groups of tags, each containing Java code.
- SCRIPTLETS
Sciptlets are sections of Java code imbedded in the HTML which the Container will place within the _jspService() method.
As such, these codes will be called when the servlet is initialized.
EXAMPLE: <% counter++; %>
Note 1: Semi-colon is necessary to terminate the line of Java code within a scriptlet.
Note 2: Sciptlets are being replaced by the JSP Expression Language and are being rendered obsolete.
Further, JSP servlets can be turned off by the <scripting-invalid> tag placed within the DD.
Note 3: Since the code is placed within the _jspService(), all variables declared in scriptlets are local to that method.
- EXPRESSIONS
Expressions are sections of Java code which will evaluate to another value. (Yes, I know it's an ugly sentence.)
In these cases, the value of the code will be determined and be inserted into the HTML code.
EXAMPLE: <%= 12*2 %> will display the numeric value 24.
<%= Class.getVariable() %> will display the value returned by the getVaiable() method.
Note 1: The content of expressions become the input parameters of a PrintWriter.out(). As such, no semi-colon should be included within the tags.
- DECLARATION
Declarations are used to declare code which will be placed outside of (and prior to) the _jspService() method.
As such, declarations are used to declare new methods and global variables.
EXAMPLE: <%! int counter = 0; %> will declare a global counter varialbe within the servlet.
<%! public String getName() {
return this.name; } %> inserts a getter method
- DIRECTIVES
Directives are used to give special instructions to the Container.
Directives come in three types, page, include, and taglib.
- PAGE
Page directives are used define page-specific properties.
The page directive contains 13 attributes.
EXAMPLE: <%@ page import = "com.my.package.*" %> writes an import statement to the servlet.
Note: Semi-colons are not placed between the tags.
- INCLUDE
Allows external text or files to be added to the page produced by the servlet.
Often used to embed navigation bars or other boiler plate code to a page.
EXAMPLE: <%@ include file="myPageHeader.html" %>
- TAGLIB
Used to define tag libraries available to the JSP.
EXAMPLE <%@ taglib tagdir="/WEB_INF/tags/myTags" prefix="myTags" %>