1 JSP script Element
JSP script elements are used to insert Java code, which will appear in the Servlet generated by the current JSP page. There are three types of script elements:
Expression format <% = expression %>: calculates the expression and outputs its results.
Scriptlet format <% code %>: inserts the code into the Servlet service method.
Declaration format <%! Code %>: add the declaration to the Servlet class (except any method ).
The following describes their usage in detail.
JSP expressions
JSP expressions are used to insert Java data directly to the output. The syntax is as follows:
<% = Java Expression %>
The result obtained by calculating the Java expression is converted to a string and inserted to the page. Computing is performed at runtime (when the page is requested), so you can access all the information related to the request. For example, the following code shows the date/time requested by the page:
Current time: <% = new java. util. Date () %>
To simplify these expressions, JSP predefines a set of object variables that can be used directly. We will introduce these implicitly declared objects in detail later, but for JSP expressions, the most important objects and their types are as follows:
Request: HttpServletRequest;
Response: HttpServletResponse;
Session: The HttpSession associated with the request
Out: PrintWriter (buffer version, JspWriter), used to send the output to the client
The following is an example:
Your hostname: <% = request. getRemoteHost () %>
Finally, if XML is used, JSP expressions can also be written in the following form:
<Jsp: expression>
Java Expression
</Jsp: expression>
Remember that the XML element is different from the HTML element. XML is case sensitive, so it must be in lower case. For instructions on XML syntax, see XML tutorial
JSP Scriptlet
If you want to complete a task more complex than inserting a simple expression, you can use JSP Scriptlet. JSP Scriptlet allows you to insert arbitrary Java code into the Servlet. The JSP Scriptlet syntax is as follows:
<% Java Code %>
Like JSP expressions, Scriptlet can also access all predefined variables. For example, if you want to output content to the result page, you can use the out variable:
<%
String queryData = request. getQueryString ();
Out. println ("Attached GET data:" + queryData );
%>
Note that the code in Scriptlet will be copied to the Servlet, and the static HTML (template text) before and after the Scriptlet will be converted to the println statement. This means that the Java statements in the Scriptlet are not necessarily complete. blocks that are not closed will affect static HTML outside the Scriptlet. For example, the following JSP snippets mix template text with Scriptlet:
<% If (Math. random () <0.5) {%>
Have a <B> nice </B> day!
<%} Else {%>
Have a <B> lousy </B> day!
<% }%>
The preceding JSP code is converted into the following Servlet code:
If (Math. random () <0.5 ){
Out. println ("Have a <B> nice </B> day! ");
} Else {
Out. println ("Have a <B> lousy </B> day! ");
}
To use the character "%>" inside the Scriptlet, you must write it as "% \> ". Note that the XML equivalent expression of <% code %> is:
<Jsp: scriptlet>
Code
</Jsp: scriptlet>
JSP Declaration
JSP declarations are used to define the methods and member variables for inserting Servlet classes. The syntax is as follows:
<%! Java Code %>
Since the Declaration does not have any output, they are often used together with JSP expressions or Scriptlet. For example, the following JSP code snippet outputs the number of requests on the current page since the server is started (or the Servlet class has been modified and reloaded:
<%! Private int accessCount = 0; %>
Page access times since the server is started:
<% = ++ AccessCount %>
Like Scriptlet, to use the string "%>", replace it with "% \>. Last, <%! The XML equivalent expression of code %> is:
<Jsp: declaration>
Code
</Jsp: declaration>
2 JSP commands
JSP commands affect the overall structure of Servlet classes. The syntax is generally as follows:
<% @ Directive attribute = "value" %>
In addition, you can combine multiple attributes of the same command, for example:
<% @ Directive attribute1 = "value1"
Attribute2 = "value2"
...
AttributeN = "valueN" %>
JSP commands can be divided into two types: the first is the page command, used to complete the following types of tasks: import the specified class, the custom Servlet superclass, and so on; the second is the include command, it is used to introduce other files when converting JSP files into servlets. The JSP specification also mentions the taglib command, which aims to enable JSP developers to define their own tags, but JSP 1.0 does not support this command. Hopefully it will become one of the main improvements of JSP 1.1.
Page command
The page directive defines one or more of the following attributes, which are case sensitive.
Import = "package. class", or import = "package. class1,..., package. classN ":
Used to specify which packages to import, such as <% @ page import = "java. util. *" %>. Import is the only property that can appear more than once.
ContentType = "MIME-Type" or contentType = "MIME-Type; charset = Character-Set ":
This attribute specifies the MIME type of the output. The default value is text/html. For example, the following command:
<% @ Page contentType = "text/plain" %>.
The same effect as the following Scriptlet:
<% Response. setContentType ("text/plain"); %>
IsThreadSafe = "true | false"
The default value "true" indicates that the Servlet is processed in a standard way, That is, assuming that the developer has synchronized access to instance variables, a single Servlet instance simultaneously processes multiple requests. If the value is false, it indicates that the Servlet should implement SingleThreadModel. The request either enters one by one, or multiple parallel requests are processed by different Servlet instances.
Session = "true | false"
The default value "true" indicates that the predefined variable session (HttpSession type) should be bound to an existing session. If there is no existing session, create a new one and bind the session variable. If the value is false, the session is not used. An error occurs when you attempt to access the variable session.
Buffer = "size kb | none"
This attribute specifies the cache size of JspWrite out. The default value is related to the server, but it should be at least 8 KB.
Autoflush = "true | false"
The default value is true, indicating that if the cache is full, refresh it. Autoflush rarely takes the false value. The false value indicates that an exception is thrown if the cache is full. If buffer = "none", autoflush cannot be set to false.
Extends = "package. class"
This attribute specifies the superclass used by the Servlet to be generated. Be very careful when using this attribute, because the server may already be using a custom superclass.
Info = "message"
This attribute defines a string that can be extracted using the getServletInfo method.
ErrorPage = "url"
This attribute specifies a JSP page. All exceptions not captured on the current page are handled by this page.
IsErrorPage = "true | false"
This attribute indicates whether the current page can be used as an error handling page for another JSP page. The default value is false.
Language = "java"
This attribute is used to indicate the language in use. Currently, you do not need to pay attention to this attribute because the default Java language is currently the only available language.
The XML syntax for defining commands is:
<Jsp: directive. directiveType attribute = value/>
For example, the following command:
<% @ Page import = "java. util. *" %>
Its XML equivalent expression is:
<Jsp: directive. page import = "java. util. *"/>
Include command
The include command is used to introduce other files when converting JSP pages into servlets. The command syntax is as follows:
<% @ Include file = "relative url" %>
The URL specified here is relative to the JSP page that sends the reference command. However, it is the same as the relative URL in the general sense, you can use a URL starting with "/" to tell the system to regard the URL as starting from the root directory of the Web server. The content that contains the file is also JSP code, that is, the file can contain static HTML, script elements, JSP commands and actions.
For example, each page of many websites has a small navigation bar. Because there are many problems with the HTML framework, the navigation bar is often made from a table at the top or left of the page, and the same HTML code is repeatedly displayed on each page of the entire website. The include command is an ideal method to implement this function. With the include command, developers no longer need to copy the HTML code for navigation to each file, so that maintenance can be completed more easily.
Because the include command imports files when JSP is converted to Servlet, if the navigation bar changes, all JSP pages that use this navigation bar must be converted to Servlet again. If the navigation bar is not changed frequently and you want to include operations as efficiently as possible, using the include command is the best choice. However, if the navigation bar is changed frequently, you can use the jsp: include action. The jsp: include action references the specified file only when a request is sent to the JSP page. For more information, see the description below.
3. Example: Application of script elements and commands
The following is a simple example of using JSP expressions, Scriptlet, declarations, and commands.
<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<HTML>
<HEAD>
<TITLE> assumerver Pages </TITLE>
</HEAD>
<Body bgcolor = "# FDF5E6" TEXT = "#000000" LINK = "# 0000EE"
VLINK = "# 551A8B" ALINK = "# FF0000">
<CENTER>
<Table border = 5 BGCOLOR = "# EF8429">
<TR> <th class = "TITLE">
JSP application instance </TABLE>
</CENTER>
<P>
Below are some dynamic content generated using various JSP functions:
<UL>
<LI> <B> expression. </B> <BR>
Your host name: <% = request. getRemoteHost () %>.
<LI> <B> JSP Scriptlet. </B> <BR>
<% Out. println ("query string:" +
Request. getQueryString (); %>
<LI> <B> Declaration (and expression). </B> <BR>
<%! Private int accessCount = 0; %>
Number of visits since the server was started: <% = ++ accessCount %>
<LI> <B> commands (and expressions). </B> <BR>
<% @ Page import = "java. util. *" %>
Current Date: <% = new Date () %>
</UL>
</BODY>
</HTML>
4. JSP predefined Variables
To simplify JSP expressions and Scriptlet code, JSP provides eight pre-defined variables (or hidden objects ). These variables are request, response, out, session, application, config, pageContext, and page.
Request
This is the HttpServletRequest associated with the request. You can view the request parameters (call getParameter), request types (GET, POST, HEAD, etc.), and the HTTP header (Cookie, Referer, ). Strictly speaking, if a request uses a Protocol other than HTTP, the request can be a subclass of ServletRequest (rather than HttpServletRequest), but it is rarely used in practice.
Response
This is the HttpServletResponse associated with the response. Note: Because the output stream (see the following out) is buffered, if the output content has been sent to the client, the common Servlet does not allow you to set the HTTP status code, but it is legal in JSP.
Out
This is the PrintWriter used to send content to the client. However, to make the response object more practical, out is the PrintWriter with the cache function, that is, JspWriter. JSP allows you to adjust the cache size through the buffer attribute of the page command, or even disable the cache.
Generally, out is used only in Scriptlet. This is because JSP expressions are automatically sent to the output stream and seldom need to explicitly reference out.
Session
This is the HttpSession object associated with the request. We have already introduced automatic session creation. We know that this object is automatically bound even if there is no session reference. However, this is an exception. If you use the session attribute of the page command to close the session, the reference to the session variable will cause an error in converting the JSP page to a Servlet.
Application
This is a ServletContext, which can also be obtained through getServletConfig (). getContext.
Config
This is the ServletConfig object of the current page.
PageContext
It is mainly used to manage page properties.
Page
It is a synonym for this and is of little use currently. It is a placeholder prepared for Java not to be the only JSP programming language.