JSP getting started tutorial (4)

Source: Internet
Author: User

Script
In some places, you may add some good and mature programs to your JSP page. Although JSP labels are powerful, it is difficult to complete some work. In this case, you can use the Script Language Segment to add JSP labels.
The JSP Engine Used supports the scripting language. For SUN's JSP reference, you must use the Java programming language to compile the script, however, other third-party JSP engines allow scripting in other languages.
How to add scripts
First, you must understand some basic rules for adding script elements to JSP pages.
1. Use the Page command to define the script on the JSP Page (the default value is Java, which is generally not required)
2. Declaration syntax <% !...... %> Declare variables and methods (functions ).
3. expression syntax <% = ...... %> Define a script language expression
4. Script syntax <% ...... %> Operation declaration, expressions, and other types of valid code segments can be performed in the Page scripting language.
5. Add %> tag at the end
Declarations, expressions, and scripts are similar, but there are also some differences. Let's use some examples to illustrate the similarities and differences.
Statement <% !...... %> Contains one or more variables and Methods Separated by semicolons.
Example: <%! Int I = 0; %>
<%! Int a, B; double c; %>
<%! Circle a = new circle (2.0); %>
Before using variables and methods on the page, you must declare
The declared range is usually a JSP page, but if the page uses the INCLUDE command to INCLUDE other pages, the range strain can be extended to the included page.
Expression <% = ...... %> You can include any legal language expressions on the page without semicolons.
Example: <% = Math. sqrt (2) %>
<% = Item [I] %>
<% = A + B + c %>
<% = New java. util. date () %>
A key difference between an expression and a script is that a semicolon is not required. If you need to use an expression in the script, you must add a plus sign.
Script <% ...... %> Any number of scripting languages you can write
Example: <% String name = null;
If (request. getParmeter ("name") = null {
%>
Remember to end with a semicolon in the script.
Guess digital games
It is very interesting to guess digital games, and you can also learn a lot about expression usage from here.
Code
Display the main screen (numguess. jsp)
<! --
Number Guess Game
Written by Jason Hunter, CTO, K & A Software
Jasonh@kasoftware.com, http://www.servlets.com
Copyright 1999, K & A Software
Distributed by Sun Microsystems with permission
-->
<% @ Page import = "num. NumberGuessBean" %>

<Jsp: useBean id = "numguess" class = "num. NumberGuessBean" scope = "session"/>
<Jsp: setProperty name = "numguess" property = "*"/>

<Html>
<Head> <title> Number Guess </title> <Body bgcolor = "white">
<Font size = 4>

<% If (numguess. getSuccess () {%>

Congratulations! You got it.
And after just <% = numguess. getNumGuesses () %> tries. <p>

<% Numguess. reset (); %>
Care to <a href = "numguess. jsp"> try again </a>?

<%} Else if (numguess. getNumGuesses () = 0) {%>

Welcome to the Number Guess game. <p>
I'm thinking of a number between 1 and 100. <p>

<Form method = get>
What's your guess? <Input type = text name = guess>
<Input type = submit value = "Submit">
</Form>

<%} Else {%>
Good guess, but nope. Try <B> <% = numguess. getHint () %> </B>.
You have made <% = numguess. getNumGuesses () %> guesses.
<P> I'm thinking of a number between 1 and 100.
<P> <form method = get>

What's your guess? <Input type = text name = guess>
<Input type = submit value = "Submit">
</Form>
<% }%>
</Font>
</Body>
</Html>

Procedure (NumberGuessBean. java)
// Number Guess Game
// Written by Jason Hunter, CTO, K & A Software
// Jasonh@kasoftware.com, http://www.servlets.com
// Copyright 1999, K & A Software
// Distributed by Sun Microsystems with permission

Package num;
Import java. util .*;
Public class NumberGuessBean {
Int answer;
Boolean success;
String hint;
Int numGuesses;
Public NumberGuessBean (){
Reset ();
}
Public void setGuess (String guess ){
NumGuesses ++;
Int g;
Try {
G = Integer. parseInt (guess );
}
Catch (NumberFormatException e ){
G =-1;
}
If (g = answer ){
Success = true;
}
Else if (g =-1 ){
Hint = "a number next time ";
}
Else if (g <answer ){
Hint = "higher ";
}
Else if (g> answer ){
Hint = "lower ";
}
}
Public boolean getSuccess (){
Return success;
}
Public String getHint (){
Return "" + hint;
}
Public int getNumGuesses (){
Return numGuesses;
}
Public void reset (){
Answer = Math. abs (new Random (). nextInt () % 100)
+ 1;
Success = false;
NumGuesses = 0;
}
}

Use scripts in JSP files
Numguess. jsp is a very interesting example of script writing. You can see that its structure is actually a very large IF ...... ELSE structure, but many clauses are written in HTML, and it looks like a large program segment.
However, you do not have to use HTML and jsp tags to write scripts like numguess. JSP. Between the <% and %> labels, you can write any number of lines of script code. In general, use as few scripts as possible to process programs, and use servlets or Beans as much as possible, in this way, your program looks very clear and clear. Then again, you have to write JSP based on your habits and hobbies. I don't have to force you to use any method. SUN's JSP detailed instruction does not specify the length of the script.

Combine scripts with tags
When using HTML and JSP tags to write scripts, be sure to "seal" The front and back labels. I don't understand. Let's take an example:
<%} Else {%> <! -- Close the JSP tag first -->

... Use JSP labels at this time...

<% }%> <! -- So you should understand it ?! -->
This may seem a bit strange at the beginning, but it ensures that the script is successfully converted when your JSP file is compiled.

So when will the script be executed?
The processing of the original JSP file is divided into two phases: one is the HTTP Compilation Time and the other is the request processing time.

During HTTP compilation, when the user reads the JSP page for the first time, the original code of JSP is compiled into a CLASS, usually servlet. The HTML Tag and JSP tag are processed at the same time. Before that, the user has not submitted any request.

The request processing time is when the user submits a request on the JSP page, then the request is sent to the server by the client by the request object, the JSP Engine executes the compiled JSP file or servlet based on the value submitted by the user.

When you use scripts in JSP pages, you must know when they will be executed. The Declaration has been processed in the HTTP compilation phase. Other scripts and expressions are also available when compiling JSP files. The expression is also executed during HTTP compilation. The expression value is converted into a string that is inserted into the JSP file and compiled together. In fact, scripts can also be used in the request stage.

Example
I now provide all the paths in the UNIX style. If you use Windows, change them to the Windows style path.
1. Assume that a digital game has been installed when TOMCAT or JSWDK is installed.
22.16.jspand .html file in ../jswdk-1.0.1/examples/num
3. The. java and. class files are in ../jswdk-1.0.1/examples/WEB-INF/jsp/bean/num
4. Open a browser, http: // machine name/examples/jsp/num/numguess. jsp

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.