JSP syntax


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


Script program

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

The syntax format of script program:

<% 代码片段 %>

Alternatively, you can write its equivalent XML statement, like the following:

<jsp:scriptlet>
   代码片段
</jsp:scriptlet>

Any text, HTML tag, JSP elements must be written outside the script program.

An example is given below, which is also the first JSP example of 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 has been installed in C:\apache- tomcat-7.0.2 directory and the running environment has been set correctly.

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

jsp_hello_world.jpg

Chinese encoding problem

If we want to display Chinese normally on the page, we need to add the following code to the head of the JSP file: <>

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

After analysis, we will 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>php中文网(php.cn)</title>
</head>
<body>
Hello World!<br/>
<%
out.println("你的 IP 地址 " + request.getRemoteAddr());
%>
</body>
</html>

So that Chinese can be displayed normally.


JSP declaration

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

The syntax format of JSP declaration:

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

Alternatively, you can also write its equivalent XML statement, like the following:

<jsp:declaration>
   代码片段
</jsp:declaration>

Program example:

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

JSP expression

The scripting language expression contained in a JSP expression is first converted into String and then inserted into the place where the expression appears.

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

The expression element can contain any expression that conforms to the Java language specification, but a semicolon cannot be used to end the expression.

The syntax format of JSP expression:

<%= 表达式 %>

Similarly, you can also write the equivalent XML statement:

<jsp: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>php中文网(php.cn)</title>
</head>
<body>
<p>
   今天的日期是: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html>

After running, the following results are obtained:

今天的日期是: 2016-6-25 13:40:07

JSP comments

JSP comments have two main functions: commenting on the code and commenting out a certain section of code.

The syntax format of JSP comments:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<%-- 该部分注释在网页中不会被显示--%> 
<p>
   今天的日期是: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html>

After running, the following results are obtained:

今天的日期是: 2016-6-25 13:41:26

The syntax rules for using comments in different situations:

## %\>               Represents static %> constant               \'             Single quotes used in attributes ##             \"
grammar describe
<%-- Comments --%>             JSP comments, the comment content will not be sent to the browser or even compiled
              <!-- Comments -->             HTML comments, you can see the comment content when viewing the source code of the web page through the browser
              <\%               Represents static <% constant
            Double quotes used in attributes
JSP directive

JSP directive is used to set properties related to the entire JSP page.

JSP instruction syntax format:

<%@ directive attribute="value" %>

There are three instruction tags:

Instructiondescribe <%@ page ... %>                 <%@ include ... %>             <%@ taglib ... %>

JSP behavior

JSP behavior tag uses XML syntax structure to control the servlet engine. It can dynamically insert a file, reuse JavaBean components, guide the user to another page, generate relevant HTML for Java plug-ins, and more.

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

<jsp:action_name attribute="value" />

Behavior tags are basically some pre-defined functions. The following table lists some available JSPs Behavior tags::

            Define the dependency attributes of the page, such as scripting language, error page, cache requirements, etc.
            Contains other files
            Introduce the definition of the tag library, which can be a custom tag
# #                 jsp:include               Used to include static or dynamic resources in the current page             jsp:useBean               Find and initialize a JavaBean component             jsp:setProperty               Set the value of JavaBean component           jsp:getProperty               Insert the value of the JavaBean component into the output               jsp:forward               Pass a request object containing the user's 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 attributes of dynamically created XML elements             jsp:body               Defines the body of a dynamically created XML element             jsp:text               Used to encapsulate template data

JSP Hidden Object

JSP supports nine automatically defined variables, which are called hidden objects by Jianghu people. The introduction of these nine implicit objects is shown in the following table:

SyntaxDescription
##               response##               outInstance of PrintWriter             sessionHttpSession               applicationInstance of ServletContext##               configInstance of class               pageContextInstance of class, provides access to all objects and namespaces of JSP pages               page               Similar to the this keyword in Java classes             An object of the Exception class, representing the corresponding exception object in the JSP page where the error occurred

Control flow statements

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

Judgment statement

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>php中文网(php.cn)</title>
</head>
<body>
<h3>IF...ELSE 实例</h3>
<% if (day == 1 | day == 7) { %>
      <p>今天是周末</p>
<% } else { %>
      <p>今天不是周末</p>
<% } %>
</body> 
</html>

The following results will be obtained after running:

IF...ELSE 实例
今天不是周末

Now let's look at the switch...case block, and if The ...else block is very different. It uses out.println(), and the entire script is installed in the tag of the script, just like the following:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%! int day = 3; %> 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<h3>SWITCH...CASE 实例</h3>
<% 
switch(day) {
case 0:
   out.println("星期天");
   break;
case 1:
   out.println("星期一");
   break;
case 2:
   out.println("星期二");
   break;
case 3:
   out.println("星期三");
   break;
case 4:
   out.println("星期四");
   break;
case 5:
   out.println("星期五");
   break;
default:
   out.println("星期六");
}
%>
</body> 
</html>

Browser access, after running, the following results are obtained :

SWITCH...CASE 实例

星期三

Loop statement

You can use Java's three basic loop types in JSP programs: for, while, and do...while.

Let's take a look at an example of a for loop, the following output of "php Chinese website" with 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>php中文网(php.cn)</title>
</head>
<body>
<h3>For 循环实例</h3>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
   <font color="green" size="<%= fontSize %>">
    php中文网
   </font><br />
<%}%>
</body> 
</html>

After running, the following results are obtained:

7B4B85CF-FE4B-43CB-AAFF-F8594AD4342C.jpg

Change the above example to use a while loop to write:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%! int fontSize; %> 
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<h3>While 循环实例</h3>
<%while ( fontSize <= 3){ %>
   <font color="green" size="<%= fontSize %>">
    php中文网
   </font><br />
<%fontSize++;%>
<%}%>
</body> 
</html>
browser access, the output result is (fontSize is initialized to 0, so one more line is output):

7B4B85CF-FE4B-43CB-AAFF-F8594AD4342C.jpg

JSP Operators

JSP supports all Java logical and arithmetic operators.

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

ObjectDescription
              requestHttpServletRequestInstance of class
HttpServletResponseInstance of class
class, used to output the results to the web page
Instance of class
class, related to application context
ServletConfig
PageContext
Exception
CategoryOperatorAssociativity
              Suffix             () [] . (dot operator)               Left to right
            One yuan ++ - - ! ~               Right to left
            Multiplyability             * / %               Left to right
            Additivity             + -             Left to right
            Shift             >> >>> <<               Left to right
            relation > >= < <=               Left to right
            Equal/unequal               == !=               Left to right
            Bits and           &               Left to right
            Bit XOR           ^               Left to right
            bit or           |               Left to right
              Logic and             &&               Left to right
            Logical OR           ||               Left to right
            Conditional judgment             ?:               Right to left
            Assignment             = += -= *= /= %= >>= <<= &= ^= |=               Right to left
            Comma               ,               Left to right

JSP literals

JSP language defines the following literals:

  •             Boolean: true and false;

  •             Integer type (int): the same as in Java;

  •             Float type (float): the same as in Java;

  •           String: Start and end with single or double quotes;

  •           Null: null.