12. Script elements, directives, and predefined variables

Source: Internet
Author: User
Tags date format define object expression variables string variable
Variables | scripts 12.1 jsp SCRIPT element

JSP script elements are used to insert Java code, which appears in the servlet generated by the current JSP page. Script elements are available in three different formats:

Expression format <%= expression%>: Evaluates an expression and outputs its results.
Scriptlet format <% Code%>: The service method that inserts the codes into the servlet.
Declaration Format <%! Code%>: Add declarations to the Servlet class (outside of any method).
Let's explain their usage in detail below.

12.1.1 JSP expression

JSP expressions are used to insert Java data directly into the output. The syntax is as follows:
<%= Java Expression%>

The result of calculating a Java expression is converted to a string and then inserted into the page. Calculations are performed at run time (when the page is requested), so all information related to the request can be accessed. For example, the following code shows the date/time the page was requested:
Current time: <%= new Java.util.Date ()%>

To simplify these expressions, the JSP pre-defined a set of object variables that can be used directly. Later, we will detail the objects of these implied declarations, but for the JSP expression, the most important objects and their types are as follows:

Request:httpservletrequest;
Response:httpservletresponse;
Session: HttpSession associated with the request
Out:printwriter (buffered version, JspWriter), used to send output to client
Here is an example:
Your hostname: <%= request.getremotehost ()%>

Finally, if you use XML, the JSP expression can also be written in the following form:
<jsp:expression>
Java Expression
</jsp:expression>


Keep in mind that XML elements are not the same as HTML. XML is case sensitive, so be sure to use lowercase. For a description of XML syntax, see the XML tutorial

12.1.2 JSP Scriptlet

If the task you are completing is more complex than inserting a simple expression, you can use the JSP scriptlet. JSP Scriptlet allows you to insert arbitrary Java code into the servlet. The JSP scriptlet syntax is as follows:
<% Java Code %>

As with JSP expressions, Scriptlet can also access all predefined variables. For example, if you want to output content to the resulting page, you can use an out variable:
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>

Note that the code in Scriptlet will be copied into the servlet, while static HTML (template text) before and after Scriptlet will be converted to println statements. This means that the Java statements within the scriptlet are not necessarily complete, and the blocks that are not closed affect static HTML outside scriptlet. For example, the following JSP fragment blends the template text with the scriptlet:
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>

The JSP code described above will be converted to 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!");
}


If you want to use the character "%>" inside the scriptlet, you must write "%\>". Also, note that the XML equivalent expression of the <% code%> is:
<jsp:scriptlet>
Code
</jsp:scriptlet>

12.1.3 JSP Declaration

The JSP declaration defines the methods and member variables that are used to insert the servlet class, with the following syntax:
<%! Java Code %>

Because declarations do not have any output, they are often used in conjunction with JSP expressions or scriptlet. For example, the following JSP code fragment outputs the number of times the current page has been requested since the server was started (or the Servlet class was changed and reloaded):
<%! private int accessCount = 0; %>
The number of page accesses since server startup is:
<%= ++accessCount %>

As with Scriptlet, if you want to use the string "%>", you must use "%\>" instead. Finally, <%! The XML equivalent expression of code%> is as follows:
<jsp:declaration>
Code
</jsp:declaration>

   12.2 JSP directives

The JSP directive affects the overall structure of the servlet class, and its syntax is generally as follows:
<%@ directive attribute="value" %>

Alternatively, you can combine multiple attributes of the same instruction, such as:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>

There are two types of JSP directives: the first is the page instruction, which is used to perform tasks such as importing the specified class, customizing the superclass of the servlet, and so on; and second, the include directive, which is used to introduce additional files when the JSP file is converted to a servlet. The JSP specification also mentions the TAGLIB directive, which is designed to allow JSP developers to define tags themselves, but JSP 1.0 does not support the directive, and hopefully it will become one of the major improvements to JSP 1.1.

12.2.1 page directive

The role of the page directive is to define one or more of the following properties, which are case-sensitive.

Import= "Package.class", or import= "Package.class1,..., package.classn":

Lets you specify which packages to import, for example: <%@ page import= "java.util.*"%>. Import is the only property that allows more than one occurrence.

Contenttype= "Mime-type" or contenttype= "Mime-type"; Charset=character-set ":

This property specifies the MIME type of the output. The default is text/html. For example, the following instruction:
<%@ page contenttype= "Text/plain"%>.
The Scriptlet effect is the same as the following:
<% Response.setcontenttype ("Text/plain"); %>

Isthreadsafe= "True|false"

The default value TRUE indicates that the servlet is handled in a standard manner, assuming that the developer has synchronized access to instance variables, and that a single servlet instance handles multiple requests concurrently. A value of FALSE indicates that the servlet should implement Singlethreadmodel, request either to be entered individually, or multiple concurrent requests handled by different servlet instances.

session= "True|false"

The default value TRUE indicates that predefined variable sessions (type httpsession) should be bound to an existing session, and if there are no existing sessions, create a new one and bind the session variable. If the value false indicates that the session is not being used, an error occurred when attempting to access the variable sessions will cause the JSP to convert to a servlet.

buffer= "Size Kb|none"

This property specifies the cache size for jspwrite out. The default value is associated with the server, but should be at least 8 KB.

Autoflush= "True|false"

The default value of TRUE indicates that it is refreshed if the cache is full. AutoFlush rarely evaluates to false, and the value of FALSE indicates that an exception is thrown if the cache is full. If buffer= "None", AutoFlush cannot take false values.

Extends= "Package.class"

This property indicates which superclass is used by the servlet that will be built. Use this property with caution, because the server may already be using a custom superclass.

info= "Message"

This property defines a string that can be extracted by the Getservletinfo method.

errorpage= "url"

This property specifies a JSP page in which all exceptions that are not captured by the current page are processed by the page.

Iserrorpage= "True|false"

This property 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 property is used to indicate the language that is being used. There is no need to focus on this attribute at this time because the default Java is the only language currently available.
The XML syntax for defining directives is:
<jsp:directive.directiveType attribute=value />

For example, the following instruction:
<%@ page import="java.util.*" %>

Its XML equivalence expression is:
<jsp:directive.page import="java.util.*" />

12.2.2 include directives

The include directive introduces other files when the JSP page is converted to a servlet. The instruction syntax is as follows:
<%@ include file="relative url" %>

The URL specified here is the URL relative to the JSP page that emits the reference instruction, however, as with relative URLs in the usual sense, you can tell the system to think of the URL as starting from the Web server root by using a URL that starts with "/". The contents of the containing file are also JSP code, that is, the containing file can contain static HTML, script elements, JSP directives, and actions.

For example, many Web sites have a small navigation bar on each page. Because of the many problems with the HTML framework, navigation bars are often made with a table at the top or left of the page, and the same HTML code repeats itself on every page of the entire site. The include directive is an ideal way to implement this functionality. With the include directive, developers do not have to copy navigation HTML code into each file, making it easier to perform maintenance work.

Because the include directive is to introduce files when the JSP is converted into a servlet, all JSP pages that use the navigation bar must be converted to a servlet if the navigation bar changes. If the navigation bar changes infrequently and you want to include the operation as efficiently as possible, using the include directive is the best option. However, if the navigation bar changes very frequently, you can use the Jsp:include action. The Jsp:include action references the specified file when it appears on the JSP page request, see the specific instructions later in this article.

   12.3 Examples: Application of script elements and directives

Here is a simple example of using JSP expressions, scriptlet, declarations, directives.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>JavaServer 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应用实例</TABLE>
</CENTER>
<P>
下面是一些利用各种JSP功能生成的动态内容:
<UL>
<LI><B>表达式.</B><BR>
你的主机名: <%= request.getRemoteHost() %>.
<LI><B>JSP Scriptlet.</B><BR>
<% out.println("查询字符串: " +
request.getQueryString()); %>
<LI><B>声明(和表达式).</B><BR>
<%! private int accessCount = 0; %>
服务器启动以来访问次数: <%= ++accessCount %>
<LI><B>指令(和表达式).</B><BR>
<%@ page import = "java.util.*" %>
当前日期: <%= new Date() %>
</UL>
</BODY>
</HTML>

  12.4 JSP Predefined variables

To simplify JSP expressions and Scriptlet code, the JSP provides 8 predefined variables (or implicitly objects). These variables are request, response, out, session, Application, config, PageContext, and page.

12.4.1 Request

This is the httpservletrequest associated with the request, through which you can view the request parameters (call GetParameter), the request type (Get,post,head, etc.), and the HTTP header (Cookie,referer, etc.) of the request. Strictly speaking, if a request uses a protocol other than HTTP, requests can be subclasses of servletrequest (rather than httpservletrequest), but rarely used in practice.

12.4.2 response

This is the httpservletresponse associated with the answer. Note that because the output stream (see out below) is buffered, the normal servlet does not allow the HTTP status code to be set if the output has been sent to the client, but it is legal in the JSP.

12.4.3 out

This is the printwriter that is used to send content to the client. However, in order to make the response object more practical, out is the printwriter with caching function, namely JspWriter. JSP allows you to resize the cache through the buffer property of the page directive, and even allow caching to be turned off.

Out is typically used only within scriptlet, because the JSP expression is automatically sent to the output stream, and it is rarely necessary to explicitly reference out.

12.4.4 session

This is the HttpSession object associated with the request. We have described the automatic creation of sessions earlier, and we know that this object is automatically bound even if no session reference exists. But there is one exception, which is that if you close the session with the page instruction, then a reference to it will cause the JSP page to be converted to a servlet error.

12.4.5 Application

This is a servletcontext, or can be obtained by Getservletconfig (). GetContext ().

12.4.6 Config

This is the ServletConfig object for the current page.

12.4.7 PageContext

Primarily used to manage the properties of a page.

12.4.8 page

It is synonymous with this and is of little use at present. It is a placeholder for Java that is no longer the only JSP programming language.


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.