English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSP Syntax

This section will briefly introduce the basic syntax in JSP development.

Script Program

The script program can contain any amount of Java statements, variables, methods, or expressions, as long as they are valid in the script language.

The syntax format of the script program is:

<% Code snippet %>

Or, you can also write an equivalent XML statement, as shown below:

<jsp:scriptlet>
   Code snippet
</jsp:scriptlet>

Any text, HTML tags, or JSP elements must be written outside of the script program.

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:Please ensure that Apache Tomcat is installed at C:\apache-tomcat-7.0.2directory, and make sure the runtime environment is correctly set.

Save the above code in hello.jsp, then place it in C:\apache-tomcat-7.0.2\webapps\ROOT directory, open the browser and enter http: in the address bar://localhost:8080/Running hello.jsp gives the following result:

Chinese Encoding Issue

To display Chinese characters normally on the page, we need to add the following code to the header of the JSP file:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">

Next, we will modify the above program as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial Website(oldtoolbag.com)</title>
</head>
<body>
Hello World!<br/>
<%
out.println("Your IP address ") + request.getRemoteAddr());
%>
</body>
</html>

This way, Chinese characters can be displayed normally.

    JSP Declaration

A declaration statement can declare one or more variables or methods for use in subsequent Java code. In a JSP file, you must declare these variables and methods before you can use them.

JSP declaration syntax format:

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

Or, you can also write an equivalent XML statement, as shown below:

<jsp:declaration>
   Code snippet
</jsp:declaration>

Program example:

<%! int i = 0; %> 
<%! int a, b, c; %> 
<%! Circle a = new Circle(2.0); %>

    JSP expression

A script language expression contained in a JSP expression is first converted to a String and then inserted at the location where the expression appears.

Since the value of the expression will be converted to a String, you can use an expression in a text line without worrying whether it is an HTML tag or not.

Any expression that conforms to the Java language specification can be included in the expression element, but semicolons cannot be used to end the expression.

JSP expression syntax format:

<%= 表达式 %>

Similarly, you can also write an equivalent XML statement:

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

Program example:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial Website(oldtoolbag.com)</title>
</head>
<body>
<p>
   Today's date is: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html>

After running, the following results are obtained:

Today's date is: 2016-6-25 13:40:07

    JSP comment

JSP comments mainly have two functions: to annotate code and to comment out a section of code.

JSP comment syntax format:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial Website(oldtoolbag.com)</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 results are obtained:

Today's date is: 2016-6-25 13:41:26

Syntax rules for comments used in different situations:

Syntax                Description
                <%-- Comments --%>                JSP comments, the content of which will not be sent to the browser and will not be compiled
                <!-- Comments -->                HTML comments, the content of which can be seen when viewing the web page source code through the browser
                <\%                Represents the static <% constant
                %\>                Represents the static %> constant
                \'                Single quotes used in attributes
                \"                Double quotes used in attributes

    JSP directive

JSP directives are used to set properties related to the entire JSP page.

JSP directive syntax format:

<%@ directive attribute="value" %>

There are three types of directive tags here:

DirectivesDescription
                <%@ page ... %>                Define the dependency properties of the page, such as scripting language, error page, caching requirements, etc.
                <%@ include ... %>                Include other files
                <%@ taglib ... %>                Introduce the definition of tag libraries, which can be custom tags

    JSP behavior

JSP behavior tags use XML syntax structure to control the servlet engine. It can dynamically insert a file, reuse JavaBean components, redirect users to another page, generate relevant HTML for Java plugins, etc.

Behavior tags have only one syntax format, which strictly adheres to the XML standard:

<jsp:action_name attribute="value"> />

Behavior tags are basically some predefined functions. The following table lists some available JSP behavior tags:

SyntaxDescription
                jsp:include                Used to include static or dynamic resources in the current page
                jsp:useBean                Search and initialize a JavaBean component
                jsp:setProperty                Set the value of a JavaBean component
                jsp:getProperty                Insert the value of a JavaBean component into the output
                jsp:forward                Pass a request object containing a user request from one JSP file to another file
                jsp:plugin                Used to include Applet and JavaBean objects in the generated HTML page
                jsp:element                Dynamically create an XML element
                jsp:attribute                Define the attributes of dynamically created XML elements
                jsp:body                Define the body of dynamically created XML elements
                jsp:text                Used to encapsulate template data

    JSP implicit objects

JSP supports nine automatically defined variables, known as implicit objects in the江湖. The brief introduction of these nine implicit objects is shown in the following table:

ObjectDescription
                requestHttpServletRequestAn example of the class
                responseHttpServletResponseAn example of the class
                outPrintWriterAn example of the class, used to output results to the web page
                sessionHttpSessionAn example of the class
                applicationServletContextAn example of the class, related to the application context
                configServletConfigAn example of the class
                pageContextPageContextAn example of the class, providing access to all objects of the JSP page and the namespace
                page                Similar to the 'this' keyword in Java classes
                exceptionexception An object of the class, representing the corresponding exception object of the JSP page where an error occurs

    Control flow statements

JSP provides comprehensive support for the Java language. You can use Java API in JSP programs and even establish Java code blocks, including conditional statements and loop statements, etc.

    Conditional Statements

If…else block, please see the following example:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">
<% int day = 3; %> 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial(oldtoolbag.com)</title>
</head>
<body>
<h2>IF...ELSE Example</h2>
<% if (day == 1 | day == 7) { %>
      <p>It's the weekend today</p>
<% } else { %>
      <p>It's not the weekend today</p>
<% } %>
</body> 
</html>

After running, the following results are obtained:

IF...ELSE Example
It's not the weekend today

Now let's take a look at the switch…case block, which is quite different from the if…else block. It uses out.println() and is all enclosed within the script program tags, as shown below:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">
<% int day = 3; %> 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial(oldtoolbag.com)</title>
</head>
<body>
<h2>SWITCH...CASE Example</h2>
<% 
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 visiting the browser and running, the following results are obtained:

SWITCH...CASE Example
Wednesday

Loop Statements

In a JSP program, you can use three basic Java loop types: for, while, and do…while.

Let's take a look at the for loop example, which outputs "Basic Tutorial Website" with different font sizes as shown below:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8">
<% int fontSize; %> 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial Website(oldtoolbag.com)</title>
</head>
<body>
<h2>For Loop Example</h2>
<% for ( fontSize = 1; fontSize <= 3; fontSize++{ %>
   <font color="green" size="<%= fontSize %>">
    Basic Tutorial
   </font><br />
<%}%>
</body> 
</html>

After running, the following results are obtained:

Rewrite the following 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>Basic Tutorial(oldtoolbag.com)</title>
</head>
<body>
<h2>While loop example</h2>
<%while ( fontSize <= 3{ %>
   <font color="green" size="<%= fontSize %>">
    Basic Tutorial
   </font><br />
<%fontSize++;%>
<%}%>
</body> 
</html>

Browser access, the output result is (fontSize is initialized to 0, so an extra line is output):

    JSP Operators

JSP supports all Java logical and arithmetic operators.

The following table lists common JSP operators, sorted by priority from high to low:

CategoryOperatorAssociativity
                Postfix                ( ) [ ] . (dot operator)                Left to right
                Unary                ++ - - ! ~                Right to left
                Multiplicativity                * / %                 Left to right
                Additivity                + -                 Left to right
                Shift                >> >>> <<                  Left to right 
                Relation                > >= < <=                  Left to right
                Equal/Not equal                == !=                 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 defines the following literals:

  •             Boolean (boolean): true and false;

  •             Integer (int): Same as in Java;

  •             Float (float): Same as in Java;

  •             String (string): Starts and ends with a single or double quote;

  •             Null: null.