JSP Syntax
This section will briefly introduce the basic syntax in JSP development.
Scriptlet
A scriptlet can contain any number of Java statements, variables, methods, or expressions that are valid within the scripting language.
The syntax format for a scriptlet is:
<% code snippet %>
Alternatively, you can write an equivalent XML statement, like this:
<jsp:scriptlet>
code snippet
</jsp:scriptlet>
Any text, HTML tags, or JSP elements must be written outside the scriptlet.
Below is an example, which is also the first JSP example in this tutorial:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
Note: Ensure that Apache Tomcat is installed in the C:\apache-tomcat-7.0.2 directory and the runtime environment is correctly set up.
Save the above code in hello.jsp and place it in the C:\apache-tomcat-7.0.2\webapps\ROOT directory. Open your browser and enter http://localhost:8080/hello.jsp in the address bar. After running, you will get the following result:
Chinese Encoding Issue
If we want to display Chinese characters correctly on the page, we need to add the following code at the top of the JSP file:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Next, we modify the above program to:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
Hello World!<br/>
<%
out.println("Your IP address " + request.getRemoteAddr());
%>
</body>
</html>
This way, Chinese characters can be displayed correctly.
JSP Declaration
A declaration statement can declare one or more variables, methods for use in subsequent Java code. In a JSP file, you must declare these variables and methods before using them.
The syntax format for JSP declaration is:
<%! declaration; [ declaration; ]+ ... %>
Alternatively, you can write an equivalent XML statement, like this:
<jsp:declaration>
code snippet
</jsp:declaration>
Example program:
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression
A JSP expression contains a scripting language expression that is converted to a String and then inserted where the expression appears.
Since the value of an expression is converted to a String, you can use an expression within a text line without worrying about whether it is an HTML tag.
The expression element can contain any expression that conforms to the Java language specification, but you cannot use a semicolon to end an expression.
The syntax format for JSP expression is:
<%= expression %>
Similarly, you can write an equivalent XML statement:
<jsp:expression>
expression
</jsp:expression>
Example program:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<p>
Today's date is: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
After running, you will get the following result:
Today's date is: 2016-6-25 13:40:07
JSP Comment
JSP comments have two main purposes: annotating the code and commenting out a block of code.
The syntax format for JSP comment is:
<%-- comment --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<%-- This part of the comment will not be displayed in the web page --%>
<p>
Today's date is: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
After running, the following result is obtained:
Today's date is: 2016-6-25 13:41:26
Syntax rules for using comments in different situations:
Syntax | Description |
---|---|
<%-- Comment --%> | JSP comment, the content of the comment will not be sent to the browser or compiled |
<!-- Comment --> | HTML comment, the content of the comment can be seen when viewing the source code of the web page through the browser |
<\% | Represents a static <% constant |
%> | Represents a static %> constant |
\' | Single quote used in attributes |
\" | Double quote used in attributes |
JSP Directives
JSP directives are used to set attributes that are related to the entire JSP page.
JSP directive syntax format:
<%@ directive attribute="value" %>
There are three types of directive tags:
Directive | Description |
---|---|
<%@ page ... %> | Defines page dependencies such as scripting language, error page, caching requirements, etc. |
<%@ include ... %> | Includes other files |
<%@ taglib ... %> | Imports tag library definitions, which can be custom tags |
JSP Actions
JSP action tags use XML syntax to control the servlet engine. They can dynamically insert a file, reuse JavaBean components, redirect users to another page, generate HTML for Java plugins, etc.
Action tags have only one syntax format, which strictly adheres to the XML standard:
<jsp:action_name attribute="value" />
Action tags are essentially predefined functions. The following table lists some available JSP action tags:
Syntax | Description |
---|---|
jsp:include | Used to include static or dynamic resources in the current page |
jsp:useBean | Finds and initializes a JavaBean component |
jsp:setProperty | Sets the value of a JavaBean component |
jsp:getProperty | Inserts the value of a JavaBean component into the output |
jsp:forward | Passes a request object containing user requests from one JSP file to another |
jsp:plugin | Used to include Applet and JavaBean objects in the generated HTML page |
jsp:element | Dynamically creates an XML element |
jsp:attribute | Defines the attributes of a dynamically created XML element |
jsp:body | Defines the body of a dynamically created XML element |
jsp:text | Used to encapsulate template data |
JSP Implicit Objects
JSP supports nine automatically defined variables, known as implicit objects. A brief introduction to these nine implicit objects is given in the following table:
Object | Description |
---|---|
request | Instance of HttpServletRequest class |
response | Instance of HttpServletResponse class |
out | Instance of PrintWriter class, used to output the result to the web page |
session | Instance of HttpSession class |
application | Instance of ServletContext class, related to the application context |
config | Instance of ServletConfig class |
pageContext | Instance of PageContext class, provides access to all objects and namespaces of the JSP page |
page | Similar to the 'this' keyword in Java classes |
exception | Object of the exception class, represents the exception object corresponding to the error JSP page |
Control Flow Statements
JSP provides full support for the Java language. You can use Java APIs or even create Java code blocks in JSP programs, including conditional statements and loops, etc.
Conditional Statements
if…else block, see the following example:
<%
if (day == 1 | day == 7) {
%>
<p> Today is weekend </p>
<%
} else {
%>
<p> Today is not weekend </p>
<%
}
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%! int day = 3; %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<h3>IF...ELSE Example</h3>
<% if (day == 1 || day == 7) { %>
<p>Today is the weekend</p>
<% } else { %>
<p>Today is not the weekend</p>
<% } %>
</body>
</html>
After running, the following result is obtained:
IF...ELSE Example
Today is not the weekend
Now let's look at the switch…case block, which is quite different from the if…else block. It uses out.println() and is entirely enclosed within scriptlet tags, like this:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%! int day = 3; %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<h3>SWITCH...CASE Example</h3>
<%
switch(day) {
case 0:
out.println("Sunday");
break;
case 1:
out.println("Monday");
break;
case 2:
out.println("Tuesday");
break;
case 3:
out.println("Wednesday");
break;
case 4:
out.println("Thursday");
break;
case 5:
out.println("Friday");
break;
default:
out.println("Saturday");
}
%>
</body>
</html>
After accessing the browser, the following result is obtained:
SWITCH...CASE Example
Wednesday
Loop Statements
In JSP programs, you can use the three basic loop types of Java: for, while, and do…while.
Let's look at an example of a for loop, which outputs "tutorialpro.org" in different font sizes:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%! int fontSize; %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<h3>For Loop Example</h3>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color="green" size="<%= fontSize %>">
tutorialpro.org
</font><br />
<%}%>
</body>
</html>
After running, the following result is obtained:
For Loop Example
<font color="green" size="1">tutorialpro.org</font><br />
<font color="green" size="2">tutorialpro.org</font><br />
<font color="green" size="3">tutorialpro.org</font><br />
Modifying the above example using a while loop:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%! int fontSize=0; %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<h3>While Loop Example</h3>
<%while ( fontSize <= 3){ %>
<font color="green" size="<%= fontSize %>">
tutorialpro.org
</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>
JSP supports all Java logical and arithmetic operators.
The table below lists common JSP operators, with precedence from high to low: ```
Category | Operator | Associativity |
---|---|---|
Postfix | () [] . (dot operator) | Left to Right |
Unary | ++ - - ! ~ | Right to Left |
Multiplicative | * / % | Left to Right |
Additive | + - | Left to Right |
Shift | >> >>> << | Left to Right |
Relational | > >= < <= | Left to Right |
Equality/Inequality | == != | Left to Right |
Bitwise AND | & | Left to Right |
Bitwise XOR | ^ | Left to Right |
Bitwise OR | | | Left to Right |
Logical AND | && | Left to Right |
Logical OR | || | Left to Right |
Conditional | ?: | Right to Left |
Assignment | = += -= *= /= %= >>= <<= &= ^= |= | Right to Left |
Comma | , | Left to Right |
JSP Literals
JSP language defines the following literals:
Boolean: true and false;
Integer: same as in Java;
Floating-point: same as in Java;
String: starts and ends with single or double quotes;
Null: null.