JSP Tutorial Objective
Below is a simple JSP example (of course – a HelloWorld JSP) to start your understanding of JSPs.
<h1>Hello, JSP World</h1>
For this example, the code is stored in a file called hello.jsp. How does this JSP file differ from an HTML file? It doesn’t! The hello.jsp doesn’t contain any Java code. It is just stored as a .jsp file in with the other HTML files.
To access or “run” the JSP, a user requests the hello.jsp just like they would request hello.html via URL.
When the container encounters a JSP file for the first time it creates a servlet class. All HTML statements are encased in out.write() or out.print() statements. In this example, all the out.write or out.println statements would get placed in the service method of the generated servlet. Characters in the HTML that can cause problems in Java servlets are encoded. For example, the “ (double quote), which would normally be used to delimit a string in Java code, is encoded.
After creating the source code, the container compiles it, loads it and executes the servlet. The process of creating the source code and compiling can cause the initial run of a JSP to be much slower than all subsequent runs of the same JSP. Each JSP should be “primed” so the end user isn’t the first to visit a JSP and suffer the initial time delay. Today, many Web containers offer to prime JSPs automatically when the application is started. Ordinarily, the container does not need the generated Java source code for the servlet. After it creates the servlet class and compiles it into a .class file it discards the Java source. However, most containers offer the capability to keep the source code for developers to explore.
So where’s the Java in the JSP? In this example, there is no Java in the JSP. However, the container creates a servlet just the same.
Aside from HTML, there are three types of JSP structures.
|Types of JSP structures|
In addition, as of the JSP 2.0 specification, there is an additional expression language that Java JSP developers can use. In this chapter, JSP scripting elements and general JSP structure is covered.
There are three script elements each with its own syntax to denote it.
- Scriptlets – <% %> or <jsp:scriptlet> </jsp:scriptlet>
- Expressions – <%= %> or <jsp:expression> </jsp:expression>
- Declarations – <%! %> or <jsp:declaration> </jsp:declaration>
Notice that each has a special “<%” and standard XML “<jsp:” syntax. The XML syntax was added under JSP 1.2. Prior to JSP 1.2, the “<%” syntax had to be used which did not allow pages to be validated and created problems in XHTML pages. From a Java perspective these tags are the same.
Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.