[ Team LiB ] Previous Section Next Section

Declaring Methods and Variables with <%! %>

So far you have seen how to insert Java statements and expressions into your code. In case you haven't realized it yet, all the code within the <% %> tags and all the expressions within the <%= %> tags belong to one big Java method in the generated servlet. That is why you can use the <%= %> tags to display a variable that was declared inside the <% %> tags.

You might want to put an entire Java method into a JSP. If you try to declare a method within the <% %> tags, the Java compiler reports an error. After all, Java doesn't like it if you try to declare a method within another method. Use the <%! %> tags to enclose any declarations that belong outside the big method that generates the page. Listing 1.8 shows a JSP file that declares a separate method and then uses the <%= %> tags to display the result of calling the method.

Listing 1.8 Source Code for DeclareMethod.jsp
    public String myMethod(String someParameter)
        return "You sent me: "+someParameter;
<%= myMethod("Hi there") %>

Because it may not be obvious, Figure 1.3 shows the results of the DeclareMethod.jsp as they are displayed on the browser.

Figure 1.3. You can declare Java methods in a JSP and display results returned by those methods.


Writing to out Inside of <%! %>


The out variable is not available inside any methods you declare with the <%! tag. If you need to send data back to the browser from within a method, you must pass the out variable in as a parameter of type JspWriter.

In addition to declaring methods, you can also use the <%! %> tags to declare instance variables. These instance variables are visible to any methods you declare, and also to the code within the <% %> tags. Declaring an instance variable is as simple as this:

<%! int myInstanceVariable = 10; %>

After this variable has been declared, you can use it in other methods declared with <%! %> or within the <% %> and <%= %> tags. For example, you can display the value of myInstanceVariable this way:

    out.println("myInstanceVariable is "+ myInstanceVariable);

Likewise, you can use the <%= %> tags to display the variable this way:

MyInstanceVariable is <%= myInstanceVariable %>
    [ Team LiB ] Previous Section Next Section