<%= expression %>
expression
. Predefined variables are request
, response
, out
, session
, application
, config
, and pageContext
(available in scriptlets also). JSP Scriptlet
<% code %>
service
method. XML equivalent is
code
. JSP Declaration
<%! code %>
service
method. XML equivalent is
code
. JSP page
Directive
<%@ page att="val" %>
. Legal attributes, with default values in bold, are:
include
Directive
<%@ include file="url" %>
file="url">
.jsp:include
action to include a file at request time instead of translation time. JSP Comment
<%-- comment --%>
<-- comment -->
. The jsp:include
Action
page
directive with the include
attribute instead. Warning: on some servers, the included file must be an HTML file or JSP file, as deteRmined by the server (usually based on the file extension). The jsp:useBean
Action
or
...
Find or build a Java Bean. Possible attributes are:
jsp:setProperty
Action
jsp:getProperty
Action
jsp:forward
Action
jsp:plugin
Action
object
or EMBED
tags, as appropriate to the browser type, asking that an applet be run using the Java Plugin.
The one minor exception to the "template text is passed straight through" rule is that, if you want to have "<%
" in the output, you need to put "<%
" in the template text.
<%= expression %>
that are evaluated and inserted into the output,
<% code %>
that are inserted into the servlet's service
method, and
<%! code %>
that are inserted into the body of the servlet class, outside of any existing methods. <%= Java Expression %>
Current time: <%= new java.util.Date() %>
request
, the HttpServletRequest
;
response
, the HttpServletResponse
;
session
, the HttpSession
associated with the request (if any); and
out
, the PrintWriter
(a buffered version of type JspWriter
) used to send output to the client. Your hostname: <%= request.getRemoteHost() %>
<% Java Code %>
out
variable.
<% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %>
print
statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML outside of the scriptlets. For example, the following JSP fragment, containing mixed template text and scriptlets
<% if (Math.random() < 0.5) { %> Have a nice day! <% } else { %> Have a lousy day! <% } %>
if (Math.random() < 0.5) { out.println("Have a nice day!"); } else { out.println("Have a lousy day!"); }
%>
" inside a scriptlet, enter "%>
" instead. Finally, note that the XML equivalent of <% Code %>
is
service
method processing the request). It has the following form:
<%! Java Code %>
<%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %>
%>
", enter "%>
" instead. Finally, note that the XML equivalent of <%! Code %>
is
<%@ directive attribute="value" %>
<%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %>
page
, which lets you do things like import classes, customize the servlet superclass, and the like; and include
, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet. The specification also mentions the taglib
directive, which is not supported in JSP version 1.0, but is intended to let JSP authors define their own tags. It is expected that this will be the main new contribution of JSP 1.1.
page
Directivepage
directive lets you define one or more of the following case-sensitive attributes:
import="package.class"
or import="package.class1,...,package.classN"
. This lets you specify what packages should be imported. For example:<%@ page import="java.util.*" %>
import
attribute is the only one that is allowed to appear multiple times.
contentType="MIME-Type"
or contentType="MIME-Type; charset=Character-Set"
text/html
. For example, the directive <%@ page contentType="text/plain" %>
<% response.setContentType("text/plain"); %>
isThreadSafe="true|false"
. A value of true
(the default) indicates normal servlet processing, where multiple requests can be processed simultaneously with a single servlet instance, under the assumption that the author synchronized access to instance variables. A value of false
indicates that the servlet should implement SingleThreadModel
, with requests either delivered serially or with simultaneous requests being given separate servlet instances.
session="true|false"
. A value of true
(the default) indicates that the predefined variable session
(of type HttpSession
) should be bound to the existing session if one exists, otherwise a new session should be created and bound to it. A value of false
indicates that no sessions will be used, and attempts to access the variable session
will result in errors at the time the JSP page is translated into a servlet.
buffer="sizekb|none"
. This specifies the buffer size for the JspWriter
out
. The default is server-specific, but must be at least 8kb
.
autoflush="true|false"
. A value of true
, the default, indicates that the buffer should be flushed when it is full. A value of false
, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false
is illegal when also using buffer="none"
.
extends="package.class"
. This indicates the superclass of servlet that will be generated. Use this with extreme caution, since the server may be using a custom superclass already.
info="message"
. This defines a string that can be retrieved via the getServletInfo
method.
errorPage="url"
. This specifies a JSP page that should process any Throwable
s thrown but not caught in the current page.
isErrorPage="true|false"
. This indicates whether or not the current page can act as the error page for another JSP page. The default is false
.
language="java"
. At some point, this is intended to specify the underlying language being used. For now, don't bother with this since java
is both the default and the only legal choice. <%@ page import="java.util.*" %>
include
Directive<%@ include file="relative url" %>
For example, many sites include a small navigation bar on each page. Due to problems with HTML frames, this is usually implemented by way of a small table across the top of the page or down the left-hand side, with the HTML repeated for each page in the site. The include
directive is a natural way of doing this, saving the developers from the maintenance nightmare of actually copying the HTML into each separate file. Here's some representative code:
include
directive inserts the files at the time the page is translated, if the navigation bar changes, you need to re-translate all the JSP pages that refer to it. This is a good compromise in a situation like this, since the navigation bar probably changes infrequently, and you want the inclusion process to be as efficient as possible. If, however, the included files changed more often, you could use the jsp:include
action instead. This includes the file at the time the JSP page is requested, and is discussed in the tutorial section on JSP actions.
Using JavaServer Pages |
---|
Some dynamic content created using various JSP mechanisms:
request
, response
, out
, session
, application
, config
, pageContext
, and page
. Details for each are given below.
HttpServletRequest
associated with the request, and lets you look at the request parameters (via getParameter
), the request type (GET
, POST
, HEAD
, etc.), and the incoming HTTP headers (Cookies, Referer
, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest
other than HttpServletRequest
, if the protocol in the request is something other than HTTP. This is almost never done in practice.
HttpServletResponse
associated with the response to the client. Note that, since the output stream (see out
below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.
PrintWriter
used to send output to the client. However, in order to make the response
object (see the previous section) useful, this is a buffered version of PrintWriter
called JspWriter
. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer
attribute of the page
directive. This was discussed in Section 5. Also note that out
is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out
explicitly.
HttpSession
object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session
attribute of the page
directive (see Section 5) to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.
ServletContext
as obtained via getServletConfig().getContext()
.
ServletConfig
object for this page.
PageContext
to encapsulate use of server-specific features like higher performance JspWriter
s. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines.
this
, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java.
jsp:include
- Include a file at the time the page is requested. See Section 8.1.
jsp:useBean
- Find or instantiate a JavaBean. See Section 8.2 for an overview, and Section 8.3 for details.
jsp:setProperty
- Set the property of a JavaBean. See Section 8.4.
jsp:getProperty
- Insert the property of a JavaBean into the output. See Section 8.5.
jsp:forward
- Forward the requester to a new page. See Section 8.6.
jsp:plugin
- Generate browser-specific code that makes an OBJECT
or EMBED
tag for the Java plugin. See Section 8.7. jsp:include
Action
What's New at JspNews.com |
---|
Here is a summary of our four most recent news stories:
jsp:useBean
Actionclass
, and bind it to a variable with the name specified by id
." However, as we'll see shortly, you can specify a scope
attribute that makes the bean associated with more than just the current page. In that case, it is useful to obtain references to existing beans, and the jsp:useBean
action specifies that a new object is instantiated only if there is no existing one with the same id
and scope
. Now, once you have a bean, you can modify its properties via jsp:setProperty
, or by using a scriptlet and calling a method explicitly on the object with the variable name specified earlier via the id
attribute. Recall that with beans, when you say "this bean has a property of typeX called foo
", you really mean "this class has a method called getFoo
that returns something of type X, and another method called setFoo
that takes an X as an argument." The jsp:setProperty
action is discussed in more detail in the next section, but for now note that you can either supply an explicit value
, give a param
attribute to say that the value is derived from the named request parameter, or just list the property to indicate that the value should be derived from the request parameter with the same name as the property. You read existing properties in a JSP expression or scriptlet by calling the appropriate getXxx
method, or more commonly, by using the jsp:getProperty
action.
Note that the class specified for the bean must be in the server's regular class path, not the part reserved for classes that get automatically reloaded when they change. For example, in the Java Web Server, it and all the classes it uses should go in the classes
directory or be in a jar file in the lib
directory, not be in the servlets
directory.
Here is a very simple example that loads a bean and sets/gets a simple String
parameter.
Reusing JavaBeans in JSP |
---|
package hall; public class SimpleBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }
jsp:useBean
Details name" class="package.class" />
jsp:setProperty
and jsp:getProperty
to modify and retrieve bean properties. However, there are two other options. First, you can use the container format, namely
Body
jsp:useBean
statements result in a new bean being instantiated. Second, in addition to id
and class
, there are three other attributes that you can use: scope
, type
, and beanName
. These attributes are summarized in the following table.
Atribute Usage id
Gives a name to the variable that will reference the bean. A previous bean object is used instead of instantiating a new one if one can be found with the same id
and scope
. class
Designates the full package name of the bean. scope
Indicates the context in which the bean should be made available. There are four possible values: page
, request
, session
, and application
. The default, page
, indicates that the bean is only available on the current page (stored in the PageContext
of the current page). A value of request
indicates that the bean is only available for the current client request (stored in the ServletRequest
object). A value of session
indicates that the object is available to all pages during the life of the current HttpSession
. Finally, a value of application
indicates that it is available to all pages that share the same ServletContext
. The reason that the scope matters is that a jsp:useBean
entry will only result in a new object being instantiated if there is no previous object with the same id
and scope
. Otherwise the previously existing object is used, and any jsp:setParameter
elements or other entries between the jsp:useBean
start and end tags will be ignored. type
Specifies the type of the variable that will refer to the object. This must match the classname or be a superclass or an interface that the class implements. Remember that the name of the variable is designated via the id
attribute. beanName
Gives the name of the bean, as you would supply it to the instantiate
method of Beans
. It is permissible to supply a type
and a beanName
, and omit the class
attribute.
jsp:setProperty
Actionjsp:setProperty
to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty
after, but outside of, a jsp:useBean
element, as below:
jsp:setProperty
is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty
can appear is inside the body of a jsp:useBean
element, as below:
jsp:setProperty
is executed only if a new object was instantiated, not if an existing one was found.
There are four possible attributes of jsp:setProperty
:
Attribute Usage name
This required attribute designates the bean whose property will be set. The jsp:useBean
element must appear before the jsp:setProperty
element. property
This required attribute indicates the property you want to set. However, there is one special case: a value of "*"
means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. value
This optional attribute specifies the value for the property. String values are automatically converted to numbers, boolean
, Boolean
, byte
, Byte
, char
, and Character
via the standard valueOf
method in the target or wrapper class. For example, a value of "true"
for a boolean
or Boolean
property will be converted via Boolean.valueOf
, and a value of "42"
for an int
or Integer
property will be converted via Integer.valueOf
. You can't use both value
and param
, but it is permissible to use neither. See the discussion of param
below. param
This optional attribute designates the request parameter from which the property should be derived. If the current request has no such parameter, nothing is done: the system does not pass null
to the setter method of the property. Thus, you can let the bean itself supply default values, overriding them only when the request parameters say to do so. For example, the following snippet says "set the numberOfItems
property to whatever the value of the numItems
request parameter is, if there is such a request parameter. Otherwise don't do anything."
value
and param
, it is the same as if you supplied a param
name that matches the property
name. You can take this idea of automatically using the request property whose name matches the property one step further by supplying a property name of "*"
and omitting both value
and param
. In this case, the server iterates through available properties and request parameters, matching up ones with identical names. Here's an example that uses a bean to create a table of prime numbers. If there is a parameter named numDigits
in the request data, it is passed into the bean's numDigits
property. Likewise for numPrimes
.
NumberedPrimes
bean referenced by the jsp:useBean
element. Browse the source code directory for other Java classes used by NumberedPrimes
. The best way to try it out on-line is to start with the HTML page that acts as a front end to it.
Reusing JavaBeans in JSP |
---|
jsp:getProperty
Actionjsp:forward
Actionpage
, which should consist of a relative URL. This could be a static value, or could be computed at request time, as in the two examples below.
jsp:plugin
ActionOBJECT
or EMBED
element needed to specify that the browser run an applet using the Java plugin.
<%-- comment --%>
<!-- comment -->
<%
<%
".
%>
%>
".
'
"
%>
%>
in an attribute.
<%
<%
in an attribute.
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/10748419/viewspace-1003912/