JSP basic syntax, 3 Compilation commands, 7 Action commands, 9 built-in objects

Source: Internet
Author: User
Tags html comment

JSP basic syntax, 3 Compilation commands, 7 Action commands, 9 built-in objects
I. jsp Overview

JSPIs the abbreviation of java server page, which is essentially a simplified servlet and a dynamic web page technical standard. Jsp pages are embedded in java segments in HTML pages. applications developed using jsp can be used across platforms.

Ii. jsp basic syntax 2.1 jsp expressions

Jsp expressions are used to output information to pages. The syntax format is as follows:

<% = Expression %>

For example:<%= 5+6 %>
There must be no space between <% and =, or a space between = and the following expression.

2.2 jsp declaration ID

Declarative identifiers define global variables or methods on the jsp page. The variables and methods defined by declarative identifiers can be accessed on the entire jsp page. The syntax format is as follows:

<%! Code for declaring variables or methods %>

For example<%!String str = "test";%>
<% And! There cannot be spaces ,! There can be a space between it and the code that follows it.

2.3 jsp code segment

Code snippets are java code or script code embedded in the jsp page, which will be executed during the processing of page requests. java code can implement functions such as defining variables and flow control; script code can use jsp built-in objects to output content on the jsp page, process requests and responses, and access sessions. The syntax format of code snippets is as follows:

<% Java code or script code %>
2.4 jsp comments 2.4.1 HTML comments

HTML comment format:

<code class=" hljs xml">    <!--{cke_protected}{C}%3C!%2D%2D%20%20html%E6%B3%A8%E9%87%8A%2D%2D%3E--></code>

Html comments are not displayed on the webpage. The comments are displayed when you view the source code in the browser.

2.4.2 code snippet comments

Because the code snippets are java code or script code, the comments of the code snippets are the same as those of the java syntax. The comments of a single line are written after //, and the comments of multiple lines are written, notes for the document are written in/**And*/.

// Single line comment/* multi-line comment the first line multi-line comment the second line * // ** document comment */
2.4.3 hide comments

Html comments can be seen when you view the source code of a Web page. Strictly speaking, such comments are not safe. The hidden comments provided by jsp are not seen in the browser or when you view the source code, which is more secure.
Hide comments between <%-and %>:

<% -- Jsp injection hiding -- %>
2.4.4 dynamic comments

Embedded jsp code snippets in html comments can form Dynamic html comments.

Sample Code
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8" import="java.util.*,java.util.ArrayList"%>
Jsp basic syntax <% -- Jsp note hiding -- %> <%! String str = "test "; // jsp declaration %> <%/** document comment * // single line comment/* multi-line comment 1 multi-line comment 2 */String hello = "hello world "; out. println (hello +"
"); For (int I = 1; I <= 9; I ++) {for (int j = 1; j <= I; j ++) {out. println (I + "*" + j + "=" + j * I + "");} out. println ("
");} Out. println (str); %>

Browser access:

3. Three jsp compilation commands

The jsp Compilation instruction is a message that notifies the jsp engine. It does not generate output directly, and the Compilation instruction has a default value. There are three common compilation commands:

Page command: this command is for the current page. Include command: used to specify to include another page. Taglib command: used to define and access custom tags.
The syntax format of the compilation command is as follows:
<% @ Compile command Name property name 1 = "property value" property name 2 = "property value"... %>
3.1 page command

Common pag instruction attributes

Attribute Definition
Language = "language" It mainly specifies the language used by the JSP Container to compile the JSP page. According to the JSP 1.2 specification, only Java languages can be used currently, but other languages such as C, C ++, and Perl cannot be added in the future. The default value is Java.
Extends = "base class name" It mainly defines the parent class that the Servlet generated by this JSP page inherits.
Import = "package name" Define the Java class libraries that can be used on this JSP page
Session = "true or false" Determines whether the JSP page can use the session object. The default value is true.
Buffer = "none or size in kb" Determines whether the output stream has a buffer. The default value is an 8 KB buffer.
AutoFlush = "true or false" Determines whether the buffer of the output stream needs to be cleared automatically. If the buffer is full, an Exception will occur ). The default value is true.
IsThreadSafe = "true or false" Tell the JSP Container whether the JSP page can process multiple requests at the same time. The default value is true. If this value is set to false, the Servlet generated by escape will implement the SingleThreadModel interface.
Info = "text" Indicates information about the JSP page.
ErrorPage = "error_url" Indicates that if an exception occurs, the webpage will be directed to the specified URL again.
IsErrorPage = "true or false" Indicates whether the JSP Page is specially used to handle errors and exceptions.
ContentType = "ctinfo" The MIME type and the JSP webpage encoding method. The function is equivalent to the setContentType () method of the HttpServletResponse interface.
3.2 include command

The include command can embed an external file into the current jsp file and parse the jsp statements on this page. The include command can contain both jsp pages and static text. The syntax of the compilation command is as follows:

<% @ Include file = "jsp page or text file to be imported" %>

For example:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<%@ include file="header.jsp"%> <%@ include file="text.txt"%> <%@ include file="footer.jsp"%>

Notes for using the include command:
1. The file name cannot be a variable. The following example showsIncorrect:

<%! String url="header.jsp" %><%@ include="<%=url %>"

2. file NameNoInput parameters. The example below isIncorrect:

<%@ include file="header.jsp?username=abc" %>

3. The file path is relative to the jsp path.

3.3 taglib command

The taglib command is used to introduce some specific tag libraries. Syntax format:

<%@ taglib prefix="tagPrefix" uri="tagLibraryURI" %>

For example, use the struts tag Library:

<%@ taglib prefix="s" taglib="/struts-tags" %>

Prefix = "tagPrefix" is used to customize the tag prefix. jsp, jspx, java, javax, servlet, sun, and sunw have been retained by sun. Uri = "tagLibraryURI" unifies the resource tag library and develops a specific tag library, which can be a relative path or an absolute path.

4. Seven jsp action commands 4.1forward

The forward command is used to forward a page to another page. It can be an html page, a jsp page, or a servlet in the container.


You can use Command.
For example, when you access the index. jsp page and automatically forward it to login. jsp, you must pass the username and password in the past:
Index. jsp:

<Code class = "hljs xml"> <% @ page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <jsp: forward page = "login. jsp "> <jsp: param value =" yaopan "name =" username "> <jsp: param value =" 123456 "name =" password "> </jsp: param> </jsp: forward> <% -- press and hold the comment key on mac (Press and hold the ctrl key in windows), and then click login. the code below jsp forword is not executed -- %> website homepage </code>

In login. jsp, you can use the getParameter method to obtain the input parameter values:

<%  String name=request.getParameter("username");  String pwd=request.getParameter("password");  out.println(name);  out.println("");  out.println(pwd);%>

The address requested by the user does not change when the forword command is executed, and the page content is replaced by the forward target.

4.2 include command

The include command is used to include a page, but does not import the compilation command of the include page. Parameters can be passed through the param command:
Create an index. jsp

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

Body. jsp

4.3 useBean, setProperty, and getProperty commands 

These three commands are related to javaBean. useBean is used to initialize a Java instance on the jsp page, setProperty is the attribute value of the javaBean instance, and getProperty is used to output the attributes of the javaBean instance.
If you need to reuse a piece of code on a jsp page, you can define this code as a java method, and then call this method on multiple jsp pages to achieve Page Reuse.
The syntax format of useBean is as follows:


For example, create a Student class under the ucas.ac.cn. jspstudy package, which has three attributes: name, age, and stuId, and the corresponding setter and getter methods. Create a javaBean instance on the jsp page:

<% -- Create a Student object named stu1 -- %>

The setProperty method is used to assign values to attributes of a javaBean instance:

<% -- Assign a value to the name attribute of stu1 -- %>
<% -- Assign a value to the age attribute of stu1 -- %>

GetProperty is used to output the attribute values of the javaBean instance:

<% -- Output the name value of stu1 -- %>
<% -- Output the age value of stu1 -- %>
4.4plugin command

Plugin is mainly used to download the server-side javaBean or applet to the client for execution. It is rarely used now.

4.5param command

The param command is used to set the parameter value. The command itself cannot be used independently. A separate param command is meaningless. It can be used with the following three commands:

Jsp: include jsp: forward jsp: plugin 5. Nine built-in objects in the jsp script 5.1 application objects

Jsp and servlet cannot call each other. To solve the problem of data exchange between jsp and servlet, the web server provides four objects: application, session, request, and page. The data in the application object is valid for the entire Web application. Once jsp and servlet put the data into the application object, the data can be accessed by other jsp and servlet applications under the application.

5.2 config object

The config object indicates the current jsp configuration information, but the jsp page usually does not need to be configured. This object is rarely used in the jsp page and is used in servlet.

5.3 exception object

The exception object is an instance of Throwable, which represents errors and exceptions generated in jsp scripts and is part of the jsp page exception mechanism. When the isErrowPage attribute of the page command is set to true, the built-in exception object can be accessed.

5.4 out object

The out object is an instance of javax. servlet. jsp. JspWriter. It represents the output stream of jsp and forms an html page forever.
Out object methods:

Out. println (): After the output is complete, a line break is generated. The line feed effect is not displayed on the page and is only displayed in the source code. print (): Do not wrap out after output. getBufferSize (): output buffer size out. getRemaining (): size of the remaining output buffer out. clear (): clears the buffer and does not send data to the client out. clearBuffer (): send data to the client, and then clear the Buffer out. flush (): output buffer content out. close (): close the output stream 5.5page object.

It indicates the page itself, which is usually of little use.

5.6 pageContext object

It represents the page context. It is mainly used for jsp data sharing. You can use the pageContext object to access the variables in the range of page, request, session, and application.

5.7 request object

The request object is an important object in jsp. Each object encapsulates a user request, and all request parameters are encapsulated in the request object. The request object is an important way to obtain user request parameters. Some methods of the request object:

Request. getMethod (): name of the method to obtain the request, such as get and post. request. getRequestURI (): gets the requested resource name. for example, request access:/jspstudy/08/request. jsp request. getProtocol (): gets the protocol used by the request. for example, HTTP/1.1 request. getServerName (): the server used to obtain the request, for example, localhost. request. getServerPort (): gets the server port used by the request, for example, 8080 request. getRemoteAddr (): obtains the IP address of the client. request. getRemoteHost (): obtains the client host. request. getParameter (): Get the passed parameter value. request. getParameterValues (): If the request parameter has multiple values, this method returns an array composed of multiple values. request. setAttribute ():

Test code:

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


Request Method Name: POST requested resource:/jspstudy/08/request. the protocol used by the jsp request: server used by the HTTP/1.1 request: localhost request server port: 8080 Client IP Address: 0: 0: 0: 0: 0: 0: 0: 0: 1 client host: 0: 0: 0: 0: 0: 0: 0: 0: 1 value submitted in the form: test
5.8 response object

The response object is used by the server to respond to the client. Most of the time, the out object is used to output data to the page. However, when the out object is an instance of the JspWriter object, the Writer class for the Japanese Writer, and the Writer is a response stream, therefore, the out object cannot output non-character content. When jsp pages need to output non-character objects such as images, pdf documents, and excel, response must be used as the response output. response can also be used for redirection to add cookies to the client.

5.9 session Object

A session object indicates a user session. A user session indicates that a session starts when the client connects to the server and ends when the client is disconnected from the server.
A session is usually used to track the user's session information, such as determining whether the user is logged on or not, and tracking the user's purchased items in the shopping cart.
The attributes within the session range can be shared between multiple page jumps. Once the browser is closed and the session ends, all attributes within the session range will be lost.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.