Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JSP Syntax

JSP Syntax

This section briefly introduces the basic syntax used in JSP development.


Scriptlets

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

The syntax of a scriptlet is as follows:



<% 代码片段 %>

Alternatively, you can write the equivalent XML statement, as follows:





   代码片段



Any text, HTML tags, and JSP elements must be written outside the scriptlet.

The following is an example, which is also the first JSP example in this tutorial:





Hello World



Hello World!
<% out.println("Your IP address is " + request.getRemoteAddr()); %>

** Note:** Please make sure Apache Tomcat is installed in the C:\apache-tomcat-7.0.2 directory and the runtime environment is properly set up.

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

Chinese Character Encoding Issues

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 as follows:



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

    pageEncoding="UTF-8"%>









Runoob Tutorial(runoob.com)





Hello World!
<% out.println("你的 IP 地址 " + request.getRemoteAddr()); %>

This way, Chinese characters can be displayed correctly.


JSP Declarations

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

The syntax of a JSP declaration is as follows:



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

Alternatively, you can write the equivalent XML statement, as follows:





   代码片段



Program example:



<%! int i = 0; %> 

<%! int a, b, c; %> 

<%! Circle a = new Circle(2.0); %> 


JSP Expressions

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

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

An expression element can contain any expression that conforms to the Java language specification, but the expression cannot be ended with a semicolon.

The syntax of a JSP expression is as follows:



<%= 表达式 %>

Likewise, you can write the equivalent XML statement:





   表达式



Program example:



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

    pageEncoding="UTF-8"%>









Runoob Tutorial(runoob.com)





今天的日期是: <%= (new java.util.Date()).toLocaleString()%>

After running, you will get the following result:



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


JSP Comments

JSP comments have two main purposes: annotating code and commenting out a piece of code.

The syntax of a JSP comment is as follows:



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

    pageEncoding="UTF-8"%>









Runoob Tutorial(runoob.com)





<%-- 该部分注释在网页中不会被显示--%> 

今天的日期是: <%= (new java.util.Date()).toLocaleString()%>

After running, you will get the following result:



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

The syntax rules for using comments in different situations:

Syntax Description
<%-- comment --%> JSP comment; the comment content is not sent to the browser or even compiled
HTML comment; the comment content can be seen when viewing the page source in a browser
<% Represents a static <% constant
%> Represents a static %> constant
' Single quotes used in attributes
" Double quotes used in attributes

JSP Directives

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

The syntax of a JSP directive is as follows:



<%@ directive attribute="value" %>

There are three directive tags:

Instruction Description
<%@ page ... %> Defines the page's dependent attributes, such as scripting language, error page, buffering requirements, and so on
<%@ include ... %> Includes another file
<%@ taglib ... %> Imports the definition of a tag library, 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, direct the user to another page, generate HTML for a Java plugin, and so on.

Action tags have only one syntax format, which strictly follows the XML standard:





Action tags are basically 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 the user's request 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, commonly known as implicit objects. They are objects automatically available in a JSP page without any extra declaration or initialization.

A brief introduction to these nine implicit objects is given in the table below:

object Description
request HttpServletRequestAn instance of the class, representing the HTTP request object, containing information sent by the client to the server, such as form data and URL parameters.
response HttpServletResponseAn instance of the class, representing the HTTP response object, used to send data and responses to the client.
out JspWriterAn instance of the class, an object used to output text content to the client, typically used to generate HTML.
session HttpSessionAn instance of the class, an object representing the user session, which can be used to store and retrieve user-specific data across multiple pages.
application ServletContextAn instance of the class, representing the context of the web application, which can be used to store and retrieve global application data.
config ServletConfigAn instance of the class, containing configuration information about the current JSP page, such as initialization parameters.
pageContext PageContextAn instance of the class that provides access to all objects and namespaces of the JSP page
page Similar to the this keyword in Java classes, representing the instance of the current JSP page, which can be used to call the page's methods.
exception exception An object of the class, representing the exception object corresponding to a JSP page in which an error occurred, used to handle exceptional conditions in the JSP page and to capture and process exceptions that occur in the page.

Control Flow Statements

JSP provides full support for the Java language. You can use the Java API in JSP programs and even create Java code blocks, including conditional statements and loop statements, and so on.

Decision Statements

if…else block; see the following example:



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

    pageEncoding="UTF-8"%>

<%! int day = 3; %> 









Runoob Tutorial(runoob.com)





IF...ELSE 实例

<% if (day == 1 || day == 7) { %>

今天是周末

<% } else { %>

今天不是周末

<% } %>

After running, you will get the following result:



IF...ELSE 实例

今天不是周末

Now let's look at the switch...case block, which is very different from the if...else block; it uses out.println(), and the whole thing is enclosed in scriptlet tags, as follows:



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

    pageEncoding="UTF-8"%>

<%! int day = 3; %> 









Runoob Tutorial(runoob.com)





SWITCH...CASE 实例

<% 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("星期六"); } %>

Access it in a browser; after running, the following result is obtained:



SWITCH...CASE 实例



星期三


Loop statement

Three basic loop types in Java can be used in JSP programs: for, while, and do...while.

Let's look at an example of a for loop that outputs "Runoob Tutorial" in different font sizes:



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

    pageEncoding="UTF-8"%>

<%! int fontSize; %> 









Runoob Tutorial(runoob.com)





For 循环实例

<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %> Runoob Tutorial
<%}%>

After running, you will get the following result:

Rewrite the above example using a while loop:



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

    pageEncoding="UTF-8"%>

<%! int fontSize=0; %> 









Runoob Tutorial(runoob.com)





While 循环实例

<%while ( fontSize <= 3){ %> Runoob Tutorial
<%fontSize++;%> <%}%>

Access it in a browser; the output is as follows (fontSize is initialized to 0, so one extra line is output):

JSP Operators

JSP supports all Java logical and arithmetic operators.

The following table lists common JSP operators, in order of precedence from highest to lowest:

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 Judgment ?:  Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |=  Right to left
Comma  ,  Left to right 

JSP Literals

The JSP language defines the following literals: