The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.servlet.jsp  [18 examples] > Java Server Pages  [7 examples]

e1047. Running Java Code in a JSP Page

Java code fragments in a JSP page is called a scriptlet. This example demonstrates how to include scriptlets in a JSP page. Use the out variable to add text to the generated output:
    <%
        double rand = Math.random();
        if (rand < .1) {
            out.println("you win!");
        } else {
            out.println("try again");
        }
    %>
This example defines a method that can be used in a scriptlet in the page:
    <%!
        String getMsg() {
            double rand = Math.random();
            if (rand < .1) {
                return "you win!";
            } else {
                return "try again";
            }
        }
    %>
    <%
        // Use the method
        out.println(getMsg());
    %>
There are a number of implicit objects available to scriptlets - application, config, exception, out, pageContext, request, response, and session. These implicit objects are described in the JSP 1.2 Specification available at http://java.sun.com.

 Related Examples
e1046. The Quintessential JSP Page
e1048. Saving Data in a JSP Page
e1049. Implementing a Form in a JSP Page
e1050. Implementing a Form That Prevents Duplicate Submissions in a JSP Page
e1051. Precompiling a JSP Page
e1052. Preventing the Creation of a Session in a JSP Page

See also: Java Server Pages Headers    Java Server Pages Input    Java Server Pages Output   


© 2002 Addison-Wesley.