JSP

zhaozj2021-02-17  44

Summary

JSP Element Syntax Interpretation Notes JSP Expression <% = expression%> Expression is evaluated and placed in output XML equivalent is. expression Predefined variables are request, response, out, session, application,. . config, and pageContext (available in scriptlets also) JSP Scriptlet <% code%> code is inserted in service method XML equivalent is. code. JSP Declaration <% code%!> code is inserted in body of servlet class, outside of service method XML equivalent is . code. JSP page Directive <% @ page att = "val"%> Directions to the servlet engine about general Setup. XML Equivalent IS . Legal Attributes, with default value in bold, Are:

import = "package.class" contentType = "MIME-Type" isThreadSafe = "true | false" session = "true | false" buffer = "sizekb | none" autoflush = "true | false" extends = "package.class" info = "message" errorPage = "url" isErrorPage = "true | false" language = "java" JSP include Directive <% @ include file = "url"%> A file on the local system to be included when the JSP page is translated into a servlet XML equivalent is. The uRL must be a relative one Use the jsp:.. include action to include a file at request time instead of translation time JSP Comment <. % - Comment -%> Comment; Ignored Into Servlet. if Want A Comment In The Resultant HTML, Use Regular HTML Comment Syntax of <- Comment ->. The JSP: Include Action

. Flush = "true" /> Includes a file at the time the page is requested If you want to include the file at the time the page is translated, use the page directive with the include attribute instead Warning:. On some servers, the INCLUDED FILE MUSP FILE, AS Determined By The Server (USEBEAN Action). The JSP: Usebean Action Or ... Find or build a java bean. Possible Attributes Are:

ID = "name" scope = "Page | Request | session | Application" class = "package.class" type = "package.class" beanname = "package.class" the JSP: setProperty action Set bean properties, either explicitly or by designating that value comes from a request parameter Legal attributes arename = "beanName" property = "propertyName | *" param = "parameterName" value = "val" The jsp:. getProperty Action

Name = "PropertyName"

Value = "val" /> retrieve and output bean proties. The JSP: Forward Action

Page = "relative URL" /> Forwards Request to Another Page. The JSP: Plugin Action

Attribute = "value" *>

...

Generates Object or Embed Tags, As Appropriate To The Browser Type, Asking That An Applet Be Run Using The Java Plugin.

3. Template Text: Static HTMLIN MANY CASES, A Large Percent of Your JSP Page Just Consists of Static HTML, KNOWN AS

template text. In all respects except one, this HTML looks just like normal HTML, follows all the same syntax rules, and is simply "passed through" to the client by the servlet created to handle the page. Not only does the HTML

LOOK NORMAL, IT CAN BE

Created by wherever Tools you already it... I buy, i buy, i buy, i buy, i buy, i buy, i buy, i buy, i buy, i buy, i buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy, I buy.

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 "

4. JSP Scripting ElementsJSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page There are three forms:. Expressions of the form <% = expression%> that are evaluated and inserted into the output, Scriptlets of the form <% code%> that are inserted into the servlet's service method, and Declarations of the form <%! code%> that are inserted into the body of the servlet class, outside of any existing methods. Each of these is described IN more detail below.

4.1 JSP Expressionsa JSP

Expression IS Used to Insert Java Values ​​Directly Into The Output. It has the Following Form:

<% = Java expression%>

The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request. For example, the following shows The date / time That the the page was required:

Current Time: <% = new java.util.date ()%>

To simplify these expressions, there are a number of predefined variables that you can use These implicit objects are discussed in more detail later, but for the purpose of expressions, the most important ones are.:

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 Here's an example:.

Your hostname: <% = request.getremotehost ()%>

Finally, Note That XML Authors Can Use An Alternative Syntax for JSP Expressions:

Java Expression

Remember That XML Elements, Unlike Html Ones, Are Case Sensitive. So Be Sure Use LowerCase.4.2 JSP Scriptletsif You Want To Do Something More Complex Than Insert A Simple Expression, JSP

Scriptlets let you insert Arbitrary Code InTo The Servlet Method That Will Be Built to Generate The page. Scriptlets Have The Following Form:

<% Java code%>

Scriptlets Have Access To The Same Automatically Defined Variables As Expressions. So, For Example, IF You Want Output To Appear in The Resultant Page, you '

Out variable.

<%

String querydata = request.getQueryString ();

Out.println ("Attached Get Data: QueryData);

%>

Note That Code InsIde A Scriptlet Gets Inserted

EXACTLY As Written, And Any Static HTML (Template Text) Before or After a Scriptlet Gets Converted To

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!

<%}%>

Will Get Converted to Something Like:

IF (Math.random () <0.5) {

Out.println ("Have a nice day!");

} else {

Out.println ("Have a lousy day!");

}

If you want to use the characters

%> "Inside A Scriptlet, Enter"

% /> "INSTEAD. Finally, Note That The XML Equivalent of

<% Code%> IS

Code

4.3 JSP Declarativesa JSP

Declaration Lets You Define Methods or Fields That Get Insert Class (Outside of There W) The Request. IT HAS The Following Form:

<%! Java code%>

Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times the current page has been requested since the server booted (or the servlet class WAS Changed and Reloaded:

<%! private int accesscount = 0;%>

Accesses to page Since Server reboot:

<% = accesscount%>

As with scriptlets, if you want to use the characters

%> ", Enter"

% /> "INSTEAD. Finally, Note That The XML Equivalent of

<%! Code%> IS

Code

5. JSP DirectiveSa JSP

Directure Affects The Overall Structure of The Servlet Class. It usually has the full Form:

<% @ Directive Attribute = "Value"%>

However, You Can Also Combine Multiple Attribute Settings for a Single Directive, As Follows:

<% @ Directive Attribute1 = "Value1"

Attribute2 = "Value2"

...

Attributen = "Valuen"%>

There Are Two Main Types of Directive:

Page, Which Lets You Do Things Like Import Classes, Customize The Servlet Superclass, and The Like;

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 exercions 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.5.1 The JSP page DirectiveThe

Page Directive Lets You Define One or more of the folload case-sensitive attributes:

Import = "package.class" or import = "package.class1, ..., package.classn". this lets you specify what package for example: <% @ Page Import = "java.util. *" %> The import attribute is the only one that is allowed to appear multiple times contentType = "MIME-Type" or contentType =.. "MIME-Type; charset = Character-Set" This specifies the MIME type of the output The default is . text / html For example, the directive <% @ page contentType = "text / plain"%> has the same effect as the scriptlet <% 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 = "TR ue |. 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 Throwables 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, do not bother with this since java Is Both the default and the only legal choice. The Xml Syntax for Defin ING DIRECTIVES IS

For Example, The XML Equivalent of

<% @ page import = "java.util. *"%> IS

5.2 The JSP Include DirectiveTHIS Directive Lets You include Files at The Time The JSP Page IS Translated Into a servlet. The Directive Looks Like this:

<% @ include file = "relative URL"%>

The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash. The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.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 RepereSentative Code:

Servlet Tutorial: JavaServer Pages (JSP) 1.0 </ Title></p> <p><Meta name = "author" content = "Webmaster@somesite.com"></p> <p><Meta name = "keywords" content = "..."></p> <p><Meta name = "description" content = "..."></p> <p><Link rel = stylesheet</p> <p>Href = "site-styles.css"</p> <p>TYPE = "text / css"></p> <p></ HEAD></p> <p><Body></p> <p><% @ include file = "/ navbar.html"%></p> <p><! - part specific to this page ... -></p> <p></ Body></p> <p></ Html></p> <p>Note That Since The</p> <p>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 thejsp:. include action instead This includes the file at the time the JSP page is requested, and IS discussed in</p> <p>The Tutorial Section on JSP Actions.</p> <p>6. Example Using Scripting Elements and Directiveshere Is A Simple Example Showing The Use of JSP Expressions, Scriptlets, Declarations, and Directives. You can Also</p> <p>Download the Source OR</p> <p>Try it on-line.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Using JavaServer Pages </ Title></p> <p><Meta name = "author" content = "Marty Hall - Hall@apl.jhu.edu"></p> <p><Meta name = "keywords"</p> <p>Content = "JSP, JavaServer Pages, Servlets"></p> <p><Meta name = "description"</p> <p>Content = "a Quick Example of The Four Main JSP Tags."></p> <p><Link rel = stylesheet</p> <p>HREF = "my-style-sheet.css"</p> <p>TYPE = "text / css"></p> <p></ HEAD></p> <p><Body bgcolor = "# fdf5e6" text = "# 000000" link = "# 000EE"</p> <p>VLINK = "# 551a8b" alink = "# ff0000"></p> <p><Center></p> <p><Table Border = 5 BGColor = "# EF8429"></p> <p><TR> <TH Class = "Title"></p> <p>Using JavaServer Pages </ TABLE></p> <p></ Center></p> <p><P></p> <p>Some Dynamic Content Created Using Various JSP Mechanisms:</p> <p><Ul> <li> <b> expness. </ B> <br></p> <p>Your Hostname: <% = Request.getRemoteHost ()%>.</p> <p><Li> <b> scriptlet. </ B> <br></p> <p><% out.println ("Attached Get Data:" </p> <p>Request.getQueryString ());%></p> <p><Li> <b> Declaration (Plus expression). </ B> <br></p> <p><%! private int accesscount = 0;%></p> <p>Accesses to Page Since Server Reboot: <% = AccessCount%></p> <p><Li> <b> Directive (Plus expression). </ B> <br></p> <p><% @ Page Import = "java.util. *"%></p> <p>Current Date: <% = new date ()%></p> <p></ Ul></p> <p></ Body></p> <p></ Html></p> <p>Here's a Typical Result:</p> <p>7. Predefined Variablesto Simplify Code In JSP Expressions and ScriptleTs, You Are Supplied with Eight Automatically Defined Variables, Sometimes Called</p> <p>Implicit Objects. The Available Variables Are</p> <p>REQUEST,</p> <p>Response,</p> <p>OUT,</p> <p>Session,</p> <p>Application,</p> <p>CONFIG,</p> <p>PageContext, And</p> <p>Details for Each Are Given Below.</p> <p>7.1 Requestthis is the</p> <p>HttpservletRequest Associated with the request, and lets you look at the request parameters (VIA</p> <p>GetParameter, The Request Type</p> <p>GET,</p> <p>POST,</p> <p>HEAD, ETC.), and the incoming http headers (cookies,</p> <p>Referer, ETC.). Strictly Speaking, Request Is Allowed to Be a Subclass of</p> <p>ServletRequest Other Than</p> <p>HTTPSERVLETREQUEST, IF The Protocol in The Request Is Something Other Than Http. This is Almost Never Done in Practice.</p> <p>7.2 Responsethis is the</p> <p>HttpservletResponse Associated with the response to the client. Note That, Since The Output Stream (See</p> <p>Out below is buffered, IT</p> <p>IS legal to set http status cots and response headers, Even though this is not permitted in regular servlets overce any output Has Been Sent to the client.7.3 outthis is the thecl</p> <p>Printwriter Used to send output to the client. However, in order to make the</p> <p>Response Object (see the previous section) USEful, this is a buffered version of</p> <p>PrintWriter Called</p> <p>JSPWriter. Note That You Can Adjust The Buffer Size, or Even Turn Buffering Off, Through Use of The</p> <p>Buffer Attribute of The</p> <p>Page Directive. this Was Discussed in</p> <p>Section 5. Also Note That</p> <p>Out IS Used Almost Exclusively in ScriptleTs, Since JSP Expressions Automatical Get Placed In The Output Stream, And Thus Rarely Need To Refer to</p> <p>Out expriCITLY.</p> <p>7.4 sessionthis is the</p> <p>Httpsession Object Associated with the request. Recall That Sessions Are Created Automatic or So this Variable Is Bound Even if The a no incoming session reason. The one of you</p> <p>Session attribute of the</p> <p>Page Directive (See</p> <p>.,..............................</p> <p>7.5 ApplicationThis Is The</p> <p>ServletContext As Obtained Via</p> <p>GetServletConfig (). getContext ().</p> <p>7.6 Configthis Is The</p> <p>ServletConfig Object for this page.</p> <p>7.7 PageContextJsp Introducesd a New Class Called</p> <p>PageContext to Encapsulate Use of Server-Specific Features Like Higher Performance</p> <p>JSPWriters. The idea is what, if you access The THROUGH THIS Class Rather Than Directly, Your Code Will Still Run on "Regular" servlet / jsp engines.</p> <p>7.8 PageThis IS SIMPLY A SYNONYM for</p> <p>This, and is not very useful in java. it is created as a placeholder for the Time When the Scripting Language Could Be Something Other Than Java.8. ActionSjsp</p> <p>. Actions use constructs in XML syntax to control the behavior of the servlet engine You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin Available actions include.:</p> <p>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. These actions are described in more detail below. Remember that, as with XML in general, the element and attribute names are case sensitive.</p> <p>8.1 The JSP: Include ActionThis Action Lets You Insert Files Into The Page Being Generated. The Syntax Looks Like this:</p> <p><jsp: include page = "relative url" flush = "true" /></p> <p>Unlike the</p> <p>include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. This pays a small penalty in efficiency, and precludes the included page from containing general JSP code (it can not set HTTP headers, for example), but it gains significantly in flexibility. for example, here is a JSP page that inserts four different snippets into a "What's New?" Web page. Each time the headlines change, authors only need To Update The Four Files, But Can Leave The Main JSP Page Unchanged.Whatsnew.jspyou Can Also</p> <p>Download the Source OR</p> <p>Try it on-line.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> what's new </ title></p> <p><Link rel = stylesheet</p> <p>HREF = "my-style-sheet.css"</p> <p>TYPE = "text / css"></p> <p></ HEAD></p> <p><Body bgcolor = "# fdf5e6" text = "# 000000" link = "# 000EE"</p> <p>VLINK = "# 551a8b" alink = "# ff0000"></p> <p><Center></p> <p><Table Border = 5 BGColor = "# EF8429"></p> <p><TR> <TH Class = "Title"></p> <p>What's new at jspnews.com </ table></p> <p></ Center></p> <p><P></p> <p>Here Is A Summary of Our Four Most News Stories:</p> <p><O></p> <p><Li> <jsp: include page = "news / item1.html" Flush = "true" /></p> <p><Li> <jsp: include page = "news / item2.html" Flush = "true" /></p> <p><Li> <jsp: include page = "news / item3.html" Flush = "true" /></p> <p><Li> <jsp: include page = "news / item4.html" flush = "true" /></p> <p></ Ol></p> <p></ Body></p> <p></ Html></p> <p>Here's a typical result: 8.2 The jsp: useBean ActionThis action lets you load in a JavaBean to be used in the JSP page This is aa very useful capability because it lets you exploit the reusability of Java classes without sacrificing the convenience that JSP adds over. Servlets Alone. The Simplest Syntax for Specifying That A Bean Should Be Used IS:</p> <p><jsp: usebean id = "name" class = "package.class" /></p> <p>THIS USUALLY Means "Instantiate An Object of The Class Specified by</p> <p>Class, and bind it to a variable with the name specified by</p> <p>ID. "However, as we'll See Shortly, You CAN Specify A</p> <p>Scope Attribute That Makes The Bean Associated with More Just The Current Page. in That Case, IT IS Useful To Obtain References To EXISTING BEANS, AND THE</p> <p>JSP: Usebean action specifies That a new object is instantiated only if there is no example</p> <p>ID and</p> <p>Scope. Now, Once You Have A Bean You Can Modify ITS Properties VIA</p> <p>JSP: setproperty, or by using a scriptlet and calling a method explicitly on the object with the variable name specified earlier via the</p> <p>Id attribute. recall tria with beans, means "this bean Has a property of type</p> <p>X called</p> <p>Foo ", you really mean" this class haas a method caled</p> <p>Getfoo That Returns Something Of Type</p> <p>X, And Another Method Called</p> <p>Setfoo Takes An</p> <p>X as an argument. "THE</p> <p>JSP: SetProperty Action Is Discussed in More Detail in The next section, but for now, you can piece</p> <p>Value, Give A</p> <p>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 appropriategetxxx method, or more commitly, by using the</p> <p>JSP: getProperty action.</p> <p>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.</p> <p>Here Is a Very Simple Example That Loads a bean and sets / gets a Simple String Parameter.</p> <p>Beantest.jspyou Can Also</p> <p>Download the Source OR</p> <p>Try it on-line.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Reusing JavaBeans in JSP </ Title></p> <p><Link rel = stylesheet</p> <p>HREF = "my-style-sheet.css"</p> <p>TYPE = "text / css"></p> <p></ HEAD></p> <p><Body></p> <p><Center></p> <p><Table border = 5></p> <p><TR> <TH Class = "Title"></p> <p>Reusing JavaBeans in JSP </ Table></p> <p></ Center></p> <p><P></p> <p><jsp: usebean id = "test" class = "Hall.SIMPLEBean" /></p> <p><JSP: setProperty Name = "Test"</p> <p>Property = "Message"</p> <p>Value = "Hello WWW" /></p> <p><H1> Message: <i></p> <p><jsp: getproperty name = "test" property = "message" /></p> <p></ I> </ h1></p> <p></ Body></p> <p></ Html></p> <p>SimpleBean.javahere's The Source Code for the Bean Used in The Beantest JSP page. You can alsodownload the source.</p> <p>Package Hall;</p> <p>Public class SimpleBean {</p> <p>Private string message = "no message specified";</p> <p>Public string getMessage () {</p> <p>Return (Message);</p> <p>}</p> <p>Public void setmessage (string message) {</p> <p>THIS.MESSAGE = Message;</p> <p>}</p> <p>}</p> <p>Here's a Typical Result:</p> <p>8.3 More JSP: Usebean Detailsthe SimpleSt Way To Use a bean is to us</p> <p><jsp: usebean id = "name" class = "package.class" /></p> <p>To load the bean, then us</p> <p>JSP: setProperty and</p> <p>JSP: GetProperty to Modify And Retrieve Bean Properties. However, There Are Two Other Options. First, You Can Use the Container Format, Namely</p> <p><jsp: usebean ...> body </ jsp: usebean> to indeicate what</p> <p>Body Portion SHOULD BEESTANTIATED, NOT IID. AS Discussed Below, Beans Can Be Shared, SO NOT ALL</p> <p>JSP: Usebean Statements Result in a new bean being instantiated. second, in addition to</p> <p>ID and</p> <p>Class, There Are Three Other Attributes That You Can Use:</p> <p>SCOPE,</p> <p>Type, And</p> <p>Beanname. The Following Table.</p> <p>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 i . S 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 IT IS permissible to suppredive a type and a beanname, and omit the class attribute.8.4 the JSP: setProperty ActionYou Use</p> <p>JSP: setProperty to Give Values ​​To Properties of Beans That Have Been Reference Earlier. You can do this in two contex: setproperty afters, but outside of, a</p> <p>JSP: Usebean Element, AS Below:</p> <p><jsp: usebean id = "myname" ... /></p> <p>...</p> <p><jsp: setproperty name = "myname"</p> <p>Property = "SomeProperty" ... /></p> <p>In this case, the</p> <p>JSP: setProperty Is Executed Regardless of WHETHER A New Bean Was Instantiated or An EXISTING BEAN WAS found in which</p> <p>JSP: SetProperty Can Appear is Inside the Body of A</p> <p>JSP: Usebean Element, AS Below:</p> <p><JSP: Usebean ID = "MyName" ...></p> <p>...</p> <p><jsp: setproperty name = "myname"</p> <p>Property = "SomeProperty" ... /></p> <p></ jsp: usebean></p> <p>Here, the</p> <p>JSP: setProperty is Executed Only if A New Object Was Instantiated, Not if An existing one was found.</p> <p>There Are Four Possible Attributes of JSP: SetProperty:</p> <p>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 property will be converted via Boolean Boolean.valueOf, and a value of "42" for an int or property will be converted via Integer Integer.valueOf. You can not use both value and param, but it is permissible to use neither. See the discussion of param below. param This optional attribute designates the reque st 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 do not do anything." <jsp: setproperty name = "Orderbean" property = "numberofItems"</p> <p>param = "numItems" /> If you omit both 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 The is a parameter namednumdigits in the request data, it is passed Into the bean's</p> <p>Numdigits Property. LiKewise for</p> <p>Numprimes.</p> <p>JSPprimes.jspto Download The JSP Source, Right Click ON</p> <p>The Source Code Link. You Can Also Download</p> <p>The Source Code for the Numberedprimes Bean Reference by THE</p> <p>JSP: Usebean Element. Browse the</p> <p>Source Code Directory for Other Java Classes Used By</p> <p>NumberedPrimes. The Best Way to Try Out ON-line is to start with</p> <p>The HTML Page That ACTS AS A Front End To IT.</p> <p><! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En"></p> <p><Html></p> <p><HEAD></p> <p><Title> Reusing JavaBeans in JSP </ Title></p> <p><Link rel = stylesheet</p> <p>HREF = "my-style-sheet.css"</p> <p>TYPE = "text / css"></p> <p></ HEAD></p> <p><Body></p> <p><Center></p> <p><Table border = 5></p> <p><TR> <TH Class = "Title"></p> <p>Reusing JavaBeans in JSP </ Table></p> <p></ Center></p> <p><P></p> <p><jsp: usebean id = "primetable" class = "hall.numberedprimes" /></p> <p><jsp: setproperty name = "primetable" Property = "Numdigits" /></p> <p><jsp: setProperty name = "primetable" property = "numprimes" /> Some <jsp: getproperty name = "primeTable" Property = "Numdigits" /></p> <p>Digit Primes:</p> <p><jsp: getproperty name = "primetable" Property = "numberedlist" /></p> <p></ Body></p> <p></ Html></p> <p>Here's a Typical Result:</p> <p>8.5 The jsp: getProperty ActionThis element retrieves the value of a bean property, converts it to a string, and inserts it into the output The two required attributes are name, the name of a bean previously referenced via jsp:. UseBean, and property, The Property Whose Value Should Be Insert. Here's An Example; for More Examples, See Sections</p> <p>8.2 and</p> <p>8.4.</p> <p><JSP: Usebean ID = "Itembean" ... /></p> <p>...</p> <p><Ul></p> <p><Li> Number of items:</p> <p><jsp: getproperty name = "itembean" property = "numItems" /></p> <p><Li> Cost of Each:</p> <p><jsp: getproperty name = "itembean" property = "unitcost" /></p> <p></ Ul></p> <p>8.6 The JSP: Forward ActionThis Action Lets You Forward The Request To Another Page. It Has A Single Attribute,</p> <p>..........................................</p> <p><jsp: Forward page = "/ utils / errorreporter.jsp" /></p> <p><JSP: Forward Page = "<% = SomejavaExpression%>" /></p> <p>8.7 The JSP: Plugin ActionThis Action Lets you insert The Browser-Specific</p> <p>Object OR</p> <p>Embed Element Needed to Specify That The Browser Run An Applet Using The Java Plugin.</p> <p>9. Comments and Character Quoting ConventionsThere are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially Here's a summary:. Syntax Purpose <% - comment -%> A JSP comment .. ignored by JSP-to-scriptlet translator Any embedded JSP scripting elements, directives, or actions are ignored. <-! comment -> An HTML comment Passed through to resultant HTML Any embedded JSP scripting elements, directives, or.. ActionS Are Executed Normal. </% Used in Template Text (static html) Where You Really Want "<%".% /> Used in Scripting Elements Where You Really Want "%>". / 'A Single Quote in An Attribute That uses single quotes. Remember, however, that you can use either single or double quotes, and the other type of quote will then be a regular character. / "A double quote in an attribute that uses double quotes. Remember, however, that you Can Use Either Single or Double Quotes, And The Other Type of Quote Wil .</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-30665.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="30665" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.049</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'U1nfctPfxGP1v4j_2F05EDU6XH92YVrYP0GJQRyBHlSBZu5uGt_2FVTCRvGF0cIGTX_2F_2F2_2Fy1cdAK1APFsQ_2ByVqV4Kw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>