Good articles for beginners in JSP [recommended]

Source: Internet
Author: User
Tags html comment
HTML comment

Display a comment on the client.

JSP syntax
<! -- Comment [<% = expression %>] -->
Example 1
<! -- This file displays the user login screen -->
Generate the same data as the above in the HTML source code of the client:

<! -- This file displays the user login screen -->
Example 2
<! -- This page was loaded on <% = (New java. util. Date (). tolocalestring () %> -->
In the HTML source code of the client, it is displayed:

<! -- This page was loaded on January 1, 2000 -->
Description
This annotation is similar to HTML, that is, it can be seen in "view source code.

The only difference is that you can use an expression in this comment (Example 2 ). this expression is indefinite. Different pages allow you to use various expressions as long as they are valid. For more expressions, see

Hide comments

Written in the JSP program, but not sent to the customer.

JSP syntax
<% -- Comment -- %>
Example:

Code:

<%@ page language="java" %> 
<body> 
<%-- This comment will not be visible in the page source --%> 
</body> 

Description
Characters marked with hidden comments are ignored during JSP compilation. This annotation is useful when you want to hide or annotate your JSP program. The JSP compiler does not compile the statements between <% -- and -- %>. It is not displayed in the client's browser or in the source code.

Statement

Declare valid variables and methods in JSP programs

JSP syntax
<%! Declaration; [Declaration;] +... %>
Example
<%! Int I = 0; %>
<%! Int A, B, C; %>
<%! Circle A = new circle (2.0); %>
Description
Declare the variables and methods you will use in the JSP program. You must do the same. Otherwise, an error will occur.

You can declare multiple variables and methods at a time, as long as they end with ";". Of course, these declarations are valid in Java.

When declaring methods or variables, pay attention to the following rules:

The declaration must end with ";" (scriptlet has the same rule, but the expression is different ).
You can directly use declared variables and methods included in <% @ Page %> without declaring them again.
A statement is valid only on one page. If you want to use some declarations for each page, you 'd better write them into a separate file and include them with the <% @ include %> or <JSP: Include> element.

Expression

Contains an expression that complies with the JSP syntax.

JSP syntax
<% = Expression %>
Example
<Font color = "blue"> <% = map. Size () %> </font>
<B> <% = numguess. gethint () %> </B>.
Description
The expression element represents an expression defined in the script language. It is automatically converted to a string after running, and then inserted into the expression for display at the location of the JSP file. Because the value of this expression has been converted into a string, you can insert this expression in a line of text (in the same form as ASP ).

When using expressions in JSP, remember the following:

You cannot use a semicolon (";") as the expression Terminator. But the same expression must end with a semicolon when used in scriptlet! View scriptlet
This expression element can include any expressions that are valid in Java language specification.
Sometimes expressions can also be used as attribute values of other JSP elements. An expression can become very complex and may consist of one or more expressions. The order of these expressions is from left to right.

[/B] scriptlet [/B]

Contains a valid program segment.

JSP syntax
<% Code fragment %>
Example
<%
String name = NULL;
If (request. getparameter ("name") = NULL ){
%>
<% @ Include file = "error.html" %>
<%
} Else {
Foo. setname (request. getparameter ("name "));
If (FOO. getname (). inclusignorecase ("Integra "))
Name = "Acura ";
If (name. inclusignorecase ("Acura ")){
%>
Description
A scriptlet can contain multiple JSP statements, methods, variables, and expressions.

Because of scriptlet, we can do the following:

Declare the variables or methods to be used (refer to the Declaration ).
Compile JSP expressions (reference expressions ).
Use any implicit object and any object declared with <JSP: usebean>
Compile JSP statements (if you are using Java, these statements must comply with Java Language Specification ,).
Any text, HTML Tag, JSP element must be out of scriptlet
When the JSP receives a request from the customer, the scriptlet will be executed. If the scriptlet has the displayed content, the displayed content will be included in the out object.

Include command

The JSP file contains a static file and parses the JSP statement in the file.

JSP syntax
<% @ Include file = "relativeurl" %>
Example
Include. jsp:

Code:

<body bgcolor="white"> 
<font color="blue"> 
The current date and time are 
<%@ include file="date.jsp" %> 
</font> 
</body> 

Date. jsp:

Code:
 
<%@ page import="java.util.*" %> 
<%= (new java.util.Date() ).toLocaleString() %> 

Displays in the page:
The current date and time are
Aug 30,199 9 2:38:40

Description
The <% @ include %> command inserts a file containing text or code During JSP compilation. When you use the <% @ include %> command, this process should be static. Static inclusion means that the contained file will be inserted into the JSP file, which may be a JSP file, HTML file, or text file. If the JSP file is included, the code in the JSP file will be executed.

If you only use include to include a static file. The execution result of the included file will be inserted to the <% @ include %> place In the JSP file. Once the contained file is executed, the process of the main JSP file will be restored and the next line will continue to be executed.

This contained file can be an HTML file, JSP file, text file, or just a piece of Java code, but you must note that this contained file cannot be used <HTML>,

Some <% @ include %> statements are based on special JSP compilation conditions, such:

This contained file must be open to all customers and valid for F, or it has security restrictions.
If the file is changed, the JSP file containing the file will be recompiled.
Attribute:
File = "relativeurl"
In general, the path name of this file contains a relative path. No port, protocol, or domain name is required, as shown below:

"Error. jsp" "templates/onlinestore.html" "/beans/calendar. jsp"

If the path starts with "/", the path mainly refers to the upstream and downstream path of the JSP application. If the path starts with the file name or directory name, this path is the current path of the JSP file in use.

Page command

Defines the global attributes in the JSP file.

JSP syntax
<% @ Page
[Language = "Java"]
[Extends = "package. Class"]
[Import = "{package. Class | package. *},..."]
[Session = "True | false"]
[Buffer = "None | 8kb | sizekb"]
[Autoflush = "True | false"]
[Isthreadsafe = "True | false"]
[Info = "text"]
[Errorpage = "relativeurl"]
[Contenttype = "mimetype [; charset = characterset]" | "text/html; charset = ISO-8859-1"]
[Iserrorpage = "True | false"]
%>
Example
<% @ Page import = "Java. util. *, java. Lang. *" %>
<% @ Page buffer = "5kb" autoflush = "false" %>
<% @ Page errorpage = "error. jsp" %>
Description
<% @ Page %> the command acts on the entire JSP page, and also includes static inclusion files. However, the <% @ Page %> command cannot act on dynamic include files, such as <JSP: Include>

You can use multiple <% @ Page %> commands on a page, but the attributes can only be used once. However, there is an exception, that is, the import attribute. Because the import attribute is similar to the Import Statement in Java (refer to Java language), you can use this attribute several times.

No matter where you place the <% @ Page %> command in the JSP file, it applies to the entire JSP page. However, for the sake of readability and good programming habits of the JSP program, it is best to put it on the top of the JSP file.

Attribute
Language = "Java"
Declare the type of the script language. Currently, only "Java" can be used"

Extends = "package. Class"
Indicate the full name of the Java class to be added during JSP compilation, but use it with caution, which limits the JSP compilation capability.

Import = "{package. Class | package .*},..."
List of Java packages to be imported. These packages act on program segments, expressions, and declarations.

The following package has been imported during JSP compilation, so you do not need to specify it again:

Java. Lang .*
Javax. servlet .*
Javax. servlet. jsp .*
Javax. servlet. http .*

Session = "True | false"
Sets whether the customer needs an http session. (the person who has learned asp should be familiar with it.) If it is true, the session is useful.

If it has false, you cannot use the session object and the <JSP: usebean> element that defines scope = session. This will cause errors.

The default value is true.

Buffer = "None | 8kb | sizekb"
The buffer size is used by the out object to process the JSP output to the client browser after execution. The default value is 8 KB.

Autoflush = "True | false"
Sets whether to force the output if the buffer overflows. If the value is defined as true (default value), the output is normal. If the value is set to false, if the buffer overflows, this will lead to an unexpected error. if you set the buffer to none, you cannot set autoflush to false.

Isthreadsafe = "True | false"
Sets whether JSP files can be used in multiple threads. The default value is true. That is to say, jsp can process requests from multiple users at the same time. If it is set to false, one jsp can only process one request at a time.

Info = "text"
When executing JSP, a text will be added to JSP by words. You can use servlet. getservletinfo to retrieve it.

Errorpage = "relativeurl"
Sets the JSP file for handling exception events.

Iserrorpage = "True | false"
Set whether this page is an error page. If it is set to true, you can use the exception object.

Contenttype = "mimetype [; charset = characterset]" | "text/html; charset = ISO-8859-1"
Set the MIME type. The default MIME type is text/HTML, and the default character set is ISO-8859-1.

<JSP: Forward>

Redirects an HTML file, JSP file, or program segment.

JSP syntax
<JSP: Forward page = {"relativeurl" | "<% = expression %>"}/>
Or
<JSP: Forward page = {"relativeurl" | "<% = expression %>"}>
<JSP: Param name = "parametername"
Value = "{parametervalue | <% = expression % >}"/> +
</Jsp: Forward>
Example
<JSP: Forward page = "/servlet/login"/>
<JSP: Forward page = "/servlet/login">
<JSP: Param name = "username" value = "jsmith"/>
</Jsp: Forward>
Description
<JSP: Forward> the tag transfers a request object containing user requests from one JSP file to another. <JSP: Forward> the code below the tag cannot be executed.

You can send parameters and values to the target file. In this example, the parameter name is username and the value is Scott. If you use the <JSP: param> label, the target file must be a dynamic file that can process parameters.

If you use non-buffered output, be careful when using <JSP: Forward>. If the JSP file already has data before you use <JSP: Forward>, the file execution will fail.

Attribute
Page = "{relativeurl | <% = expression %> }"
Here is an expression or a string used to indicate the file or URL you want to target. this file can be JSP, program segment, or other files (such as ASP, CGI, PHP) that can process request objects ).

<JSP: Param name = "parametername" value = "{parametervalue | <% = expression % >}"/> +
Send one or more parameters to a dynamic file. This file must be a dynamic file.

If you want to pass multiple parameters, you can use multiple <JSP: param> In a JSP file. Name specifies the parameter name and value specifies the parameter value.

<JSP: getproperty>

Obtains the bean property value, which is displayed on the page.

JSP syntax
<JSP: getproperty name = "beaninstancename" property = "propertyname"/>
Example
<JSP: usebean id = "calendar" Scope = "page" class = "employee. Calendar"/>
<H2>
Calendar of <JSP: getproperty name = "calendar" property = "username"/>
</H2>
Description
The <JSP: getproperty> element obtains the bean property value and can be used or displayed on the JSP page. before using <JSP: getproperty>, you must use <JSP: usebean> to create it.

<JSP: getproperty> elements have some restrictions:

You cannot use <JSP: getproperty> to retrieve an indexed property.
You can use <JSP: getproperty> with the JavaBeans component, but not with the enterprise Bean.
Attribute
Name = "beaninstancename"
Bean name, specified by <JSP: usebean>

Property = "propertyname"
Attribute name of the specified bean.

TIPS:
As mentioned in Sun's JSP reference, if you use <JSP: getproperty> to retrieve a value that is null, nullpointerexception will occur. If you use a program segment or expression to retrieve the value, in the browser, null is displayed ).

<JSP: Include>

Contains a static or dynamic file.

JSP syntax
<JSP: Include page = "{relativeurl | <% = expression %>}" Flush = "true"/>
Or
<JSP: Include page = "{relativeurl | <% = expression %>}" Flush = "true">
<JSP: Param name = "parametername" value = "{parametervalue | <% = expression % >}"/> +
</Jsp: Include>
Examples
<JSP: Include page = "scripts/login. jsp"/>
<JSP: Include page = "copyright.html"/>
<JSP: Include page = "/index.html"/>
<JSP: Include page = "scripts/login. jsp">
<JSP: Param name = "username" value = "jsmith"/>
</Jsp: Include>

Description
<JSP: Include> elements allow you to include dynamic files and static files. The results of these two types of files are different. If the file is only a static file, this inclusion only adds the content of the contained file to the JSP file. If the file is dynamic, the included file will be executed by the JSP compiler (similar to ASP)

You cannot determine whether a file is dynamic or static from the file name. For example, aspcn. asp may only contain some information, but does not need to be executed. <JSP: Include> these two types of files can be processed at the same time. Therefore, you do not need to determine whether the file is dynamic or static.

If the file is dynamic, you can also use <JSP: param> to pass the parameter name and parameter value.

Attribute
Page = "{relativeurl | <% = expression %> }"
The parameter is a relative path or an expression that represents a relative path.

Flush = "true"
Here you must use flush = "true". You cannot use false. The default value is false.

<JSP: Param name = "parametername" value = "{parametervalue | <% = expression % >}"/> +
<JSP: param> the clause allows you to pass one or more parameters to a dynamic file.

You can use multiple <JSP: param> on a page to pass multiple parameters,

<JSP: plugin>

Execute an applet or bean. If possible, download a Java Plug-in to execute it.

JSP syntax
<JSP: plugin
Type = "bean | applet"
Code = "classfilename"
Codebase = "classfiledirectoryname"
[Name = "instancename"]
[Archive = "uritoarchive,..."]
[Align = "bottom | top | Middle | left | right"]
[Height = "displaypixels"]
[Width = "displaypixels"]
[Hspace = "leftrightpixels"]
[Vspace = "topbottompixels"]
[Jreversion = "Maid number | 1.1"]
[Nspluginurl = "urltoplugin"]
[Iepluginurl = "urltoplugin"]>
[<JSP: Params>
[<JSP: Param name = "parametername" value = "{parametervalue | <% = expression %>}"/>] +
</Jsp: Params>]

[<JSP: fallback> text message for user </jsp: fallback>]

</Jsp: plugin>

Example
<JSP: plugin type = applet code = "molecule. Class" codebase = "/html">
<JSP: Params>
<JSP: Param name = "molecule" value = "molecules/benzene. mol"/>
</Jsp: Params>
<JSP: fallback>
<P> unable to load applet </P>
</Jsp: fallback>
</Jsp: plugin>
Description
<JSP: plugin> elements are used to play or display an object (typically an applet and bean) in a browser, and such display needs to be implemented in the browser's Java Plug-in.

When the JSP file is compiled and sent to the browser, the <JSP: plugin> element will be replaced with the <Object> or <embed> element based on the browser version. Note: <Object> is used for HTML 4.0 and <embed> for HTML 3.2.

In general, the <JSP: plugin> element specifies whether the object is an applet or bean, the class name, location, and where to download the Java Plug-in. The details are as follows:

Attribute
Type = "bean | applet"
. Type of the plug-in object to be executed. You must specify the bean or applet, because this property has no default value.

Code = "classfilename"
The name of the Java class to be executed by the Java Plug-in. It must end with. Class. This file must exist in the directory specified by the codebase attribute.

Codebase = "classfiledirectoryname"
The directory (or path) of the Java class file to be executed. If you do not provide this attribute, the Directory of the JSP file using <JSP: plugin> will be used.

Name = "instancename"
The name of the bean or applet instance, which will be called elsewhere in JSP.

Archive = "uritoarchive ,..."
Some path names separated by commas (,) are used to pre-install the classes to be used, which improves the applet performance.

Align = "bottom | top | Middle | left | right"
The position of the image, object, and Applet has the following values:

Bottom
Top
Middle
Left
Right
Height = "displaypixels" width = "displaypixels"
The length and width that the applet or bean will display. The value is a number in pixels.

Hspace = "leftrightpixels" vspace = "topbottompixels"
When the applet or bean is displayed on the left and right of the screen, the space left up and down is measured in pixels.

Jreversion = "Maid number | 1.1"
Java Runtime Environment (JRE) required for running the applet or bean. The default value is 1.1.

Nspluginurl = "urltoplugin"
The JRE that Netscape Navigator users can use, which is a standard URL such as a http://www.aspcn.com/jsp

Iepluginurl = "urltoplugin"
IE users can use JRE, this value is a standard URL, such as http://www.aspcn.com/jsp

<JSP: Params> [<JSP: Param name = "parametername" value = "{parametervalue | <% = expression % >}"/>] + </jsp: Params>
The parameter or parameter value that you need to transmit to the applet or bean.

<JSP: fallback> text message for user </jsp: fallback>
A piece of text is displayed to the user when the Java Plug-In cannot be started. If the plug-in can be started but the applet or bean cannot be started, an error message will pop up in the browser.

<JSP: setproperty>

Set the attribute value in bean.

JSP syntax
<JSP: setproperty
Name = "beaninstancename"
{
Property = "*" |
Property = "propertyname" [Param = "parametername"] |
Property = "propertyname" value = "{string | <% = expression %> }"
}
/>
Example
<JSP: setproperty name = "mybean" property = "*"/>
<JSP: setproperty name = "mybean" property = "username"/>
<JSP: setproperty name = "mybean" property = "username" value = "Steve"/>
Description
<JSP: setproperty> the element uses the setter method specified by bean to set one or more attribute values in bean. Before using this element, you must use <JSP: usebean> to declare this bean. because <JSP: usebean> and <JSP: setproperty> are linked together, and the bean instance names they use should also match (that is, in <JSP: the value of name in setproperty> should be the same as the value of ID in <JSP: usebean>)

You can use <JSP: setproperty> to set the property value in multiple ways:

Match the attributes in the bean by using all the values entered by the user (stored in the request object as parameters ).
Matches the attribute specified in bean with the value specified by the user.
Use an expression to match bean attributes at runtime
Each method for setting attribute values has its own syntax. We will explain it below.

Attributes and usage
Name = "beaninstancename"
Name of the bean instance created in <JSP: usebean>.

Property = "*"
Stores all user input values in JSP to match the attributes in bean. The attribute name in bean must be the same as the parameter name in the request object.

The parameter values transmitted from the client to the server are generally character types. These strings must be converted to other types in order to be matched in the bean, the following table lists the bean attribute types and their conversion methods.

Convert a string to another type of method. property type
Method
Boolean OR Boolean
Java. Lang. boolean. valueof (string)
Byte or byte
Java. Lang. byte. valueof (string)
Char or character
Java. Lang. character. valueof (string)
Double or double
Java. Lang. Double. valueof (string)
Integer or integer
Java. Lang. Integer. valueof (string)
Float or float
Java. Lang. Float. valueof (string)
Long or long
Java. Lang. Long. valueof (string)

If there is a null value in the parameter value of the request object, no value is set for the corresponding bean attribute. Similarly, if an attribute in the bean does not have the corresponding request parameter value, this attribute will not be set.

Property = "propertyname" [Param = "parametername"]
Use a parameter value in the request to specify a property value in the bean. In this syntax, Property specifies the bean property name And Param specifies the parameter name in the request.

If the bean property is different from the request parameter name, you must specify the property and Param. If they have the same name, you only need to specify the property.

If the query parameter value is null (or not initialized), the corresponding bean property is not set.

Property = "propertyname" value = "{string | <% = expression %> }"
Use the specified value to set bean properties. This value can be a string or an expression. If this string is used, it will be converted to the bean attribute type (view the table above ). if it is an expression, its type must be consistent with the type of the attribute value to be set.

If the parameter value is null, the corresponding property value is not set. In addition, you cannot use both PARAM and value in a <JSP: setproperty>

Tips
If you use property = "*", the bean attributes do not need to be sorted in the order in the HTML form.

<JSP: usebean>

Create a bean instance and specify its name and scope.

JSP syntax
<JSP: usebean
Id = "beaninstancename"
Scope = "Page | request | session | application"
{
Class = "package. Class" |
Type = "package. Class" |
Class = "package. Class" type = "package. Class" |
Beanname = "{package. Class | <% = expression %>}" type = "package. Class"
}
{
/> |
> Other elements </jsp: usebean>
}
Example
<JSP: usebean id = "cart" Scope = "session" class = "session. Carts"/>
<JSP: setproperty name = "cart" property = "*"/>
<JSP: usebean id = "checking" Scope = "session" class = "bank. Checking">
<JSP: setproperty name = "checking" property = "balance" value = "0.0"/>
</Jsp: usebean>

Description
<JSP: usebean> is used to locate or sample A JavaBeans component. <JSP: usebean> first tries to locate a bean instance. If this bean does not exist, <JSP: usebean> will take an example from a class or template.

To locate or sample a bean, <JSP: usebean> performs the following steps:

Attempts to locate a bean by specifying the name and range.
The variables referenced in this bean object are named by the name you specified.
If this bean is found, the reference will be stored in this variable. If you also specify the type, the bean is also set to the corresponding type.
If this bean is not found, it will be used from the class you specified and stored in a new variable. If the class name represents a template, the bean is used by Java. Beans. Beans. instantiate.
If <JSP: usebean> has been used as an example (not to locate) bean, and <JSP: usebean> and </jsp: usebean> have elements, the code will be executed.
The main body of the <JSP: usebean> element usually contains the <JSP: setproperty> element, which is used to set the bean property value. As mentioned in step 5 above, the main body of <JSP: usebean> will only be executed when <JSP: usebean> sample bean. If this bean already exists, <JSP: usebean> can locate it, so the content in the subject will not work

Attributes and usage
Id = "beaninstancename"
Confirm the bean variable in the scope you define. You can use this variable name in subsequent programs to distinguish different beans.

This variable name is case sensitive and must comply with the requirements of the scripting language you are using. in Java programming language, this provision has been stated in the Java language specification. If this bean has been created in another <JSP: usebean>, the ID value must be consistent with the original ID value.

Scope = "Page | request | session | application"
The valid range of bean and ID variable name. The default value is page, which is described as follows:

Page-you can use the bean in the JSP file that contains the <JSP: usebean> element and all static include files in the file, after the page is executed, send a response to the client or go to another file.

Request-you can use beans in any JSP file that executes the same request until the page execution is complete and the response is sent back to the client or transferred to another file. You can use the request object to access beans, such as request. getattribute (beaninstancename)

Session-from bean creation, you can use bean in any JSP file that uses the same session. this bean exists throughout the session lifecycle. Any JSP file that shares this session can use the same bean. note that session = true must be specified in the <% @ Page %> command in the JSP file of the created bean.

Application-from bean creation, you can use bean in any JSP file that uses the same application. this bean exists throughout the application lifecycle. Any JSP file that shares this application can use the same bean.
Class = "package. Class"
Use the New Keyword and the class constructor to sample a bean from a class. this class cannot be abstract and must have a common constructor without parameters. the package name is case sensitive.

Type = "package. Class"
If the bean already exists in the specified range, write the bean to a new database type. If you do not use the class or beanname to specify the type, bean will not be named by the example. Package and class names, case sensitive.

Beanname = "{package. Class | <% = expression %>}" type = "package. Class"
Use the java. Beans. Beans. instantiate method to sample a bean from a class or continuous template, and specify the bean type.

Beanname can be package or class, and its value will be passed to beans. instantiate. tupe with the same value as bean.

The package and class names are case sensitive.

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.