Sun Java Solaris Communities My SDN Account
 
Tutorials & Code Camps

NO TITLE

 
[Top] [Prev] [Next] [Bottom]

Using Scripting Elements

At some point, you will probably want to add some good, old-fashioned programming to your JSP files. The JSP tags are powerful and encapsulate tasks that would be difficult or time-consuming to program. But even so, you will probably still want to use scripting language fragments to supplement the JSP tags.

The scripting languages that are available to you depend on the JSP engine you are using. With Sun's JSP reference implementation, you must use the JavaTM programming language for scripting, but other vendors' JSP engines may include support for other scripting languages).

How To Add Scripting

First, you'll need to know a few general rules about adding scripting elements to a JSP source file:

  1. Use a page directive to define the scripting language used in the JSP page (unless you are using the Java language, which is a default value).
  2. The declaration syntax <%! .. %> declares variables or methods.
  3. The expression syntax <%= .. %> defines a scripting language expression and casts the result as a String.
  4. The scriptlet syntax <% .. %> can handle declarations, expressions, or any other type of code fragment valid in the page scripting language.
  5. When you write a scriptlet, end the scriptlet with %> before you switch to HTML, text, or another JSP tag.

The Difference Between <%, <%=, and <%!

Declarations, expressions, and scriptlets have similar syntax and usage, but also some important differences. Let's explore the similarities and differences here, with some examples.

Declarations (between <%! and %> tags) contain one or more variable or method declarations that end or are separated by semicolons:

<%! int i = 0; %>
<%! int a, b; double c; %>
<%! Circle a = new Circle(2.0); %>

You must declare a variable or method in a JSP page before you use it in the page. The scope of a declaration is usually a JSP file, but if the JSP file includes other files with the include directive, the scope expands to cover the included files as well.

Expressions (between <%= and %> tags) can contain any language expression that is valid in the page scripting language, but without a semicolon:

<%= Math.sqrt(2) %>
<%= items[i] %>
<%= a + b + c %>
<%= new java.util.Date() %>

The definition of a valid expression is up to the scripting language. When you use the Java language for scripting, what's between the expression tags can be any expression defined in the Java Language Specification. The parts of the expression are evaluated in left-to-right order. One key difference between expressions and scriptlets (which are described next and appear between <% and %> tags) is that a semicolon is not allowed within expression tags, even if the same expression requires a semicolon when you use it within scriptlet tags.

Scriptlets (between <% and %> tags) allow you to write any number of valid scripting language statements, like this:

<%
String name = null;
if (request.getParameter("name") == null) {
%>

Remember that in a scriptlet you must end a language statement with a semicolon if the language requires it.

When you write a scriptlet, you can use any of the JSP implicit objects or classes imported by the page directive, declared in a declaration, or named in a <jsp:useBean> tag.

The Number Guess Game

The Number Guess game is fun and makes good use of scriptlets and expressions, as well as using the knowledge of HTML forms you gained in the last example.

About to Guess a Number

Example Code

Displaying the Number Guess 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></head>
<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>

Handling the Guess (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;
}
}


Using Scripting Elements in a JSP File

The file numguess.jsp is an interesting example of the use of scripting elements, because it is structured as you might structure a source file, with a large
if ... else statement within scriptlet tags. The difference is that the body of each statement clause is written in HTML and JSP tags, rather than in a programming language.

You are not required to write scriptlets mingled with HTML and JSP tags, as shown in numguess.jsp. Between the <% and %> tags, you can write as many lines of scripting language code as you want. In general, doing less processing in scriptlets and more in components like servlets or Beans makes your application code more reusable and portable. Nonetheless, how you write your JSP application is your choice, and Sun's JSP 1.0 reference implementation specifies no limit on the length of a scriptlet.

Mingling Scripting Elements with Tags

When you mingle scripting elements with HTML and JSP tags, you must always end a scripting element before you start using tags and then reopen the scripting element afterwards, like this:

<% } else { %>    <!-- closing the scriptlet before the tags start -->

... tags follow ...

<% } %> <!-- reopening the scriptlet to close the language block -->

At first, this may look a bit strange, but it ensures that the scripting elements are transformed correctly when the JSP source file is compiled.

When Are the Scripting Elements Executed?

A JSP source file is processed in two stages-HTTP translation time and request processing time.

At HTTP translation time, which occurs when a user first loads a JSP page, the JSP source file is compiled to a Java class, usually a Java servlet. The HTML tags and as many JSP tags as possible are processed at this stage, before the user makes a request.

Request processing time occurs when your user clicks in the JSP page to make a request. The request is sent from the client to the server by way of the request object. The JSP engine then executes the compiled JSP file, or servlet, using the request values the user submitted.

When you use scripting elements in a JSP file, you should know when they are evaluated. Declarations are processed at HTTP translation time and are available to other declarations, expressions, and scriptlets in the compiled JSP file. Expressions are also evaluated at HTTP translation time. The value of each expression is converted to a String and inserted in place in the compiled JSP file. Scriptlets, however, are evaluated at request processing time, using the values of any declarations and expressions that are made available to them.

How To Run the Example

The instructions given here use a UNIX-style pathname. If you are working on Windows, use the same pathname with the proper separator.

1

The Number Guess example is already installed in the JSP reference implementation.

2

The .jsp and .html files are in the directory ../jswdk-1.0/examples/jsp/num .

3

The .java and .class files are in the directory ../jswdk-1.0/examples/WEB-INF/jsp/beans/num .

4

Open a Web browser and go to
http://yourMachineName/examples/jsp/num/numguess.jsp.


[Top] [Prev] [Next] [Bottom]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.

Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.