Using Java Methods in JSP Example

Using Java Methods in JSP Example

Note: It is advised to go through "JSP Scriptlet, Expression and Declaration – all in one example" to know their scope and usage in JSP coding before proceeding this topic.

We know earlier, JSP Declaration represents a global area for the whole JSP file where programmer can declare variables and methods that can be used throughout JSP code. That is, global variables and methods are declared in Declaration tag. Let us see one example and then discuss small problems that may arise while using methods.

Example on Java Methods JSP

A simple client HTML file that takes client’s name.

File Name: LearningMethods.html

This JSP uses all the four – Scriptlets, Expressions, Declaration and Methods.

JSP File Name: UsingMethods.jsp

HTML file when value is entered.

Java Methods JSP

Response of JSP

Java Methods JSP

getParameter() is the method of request, one of the 9 implicit objects, JSP supports.

Method calculate() is declared in Declaration and used from Scriptlet and Expression. Declaration represents global area.

The above single Declaration can be split into two Declarations also.

1. Can we declare a method like this?

No we cannot use. It is compilation error. The reason is scope problem of out and request objects. Read the following note.

Important Note: The code of Scriptlet and Expression is placed in the service() method of the generated Servlet. That is, the implicit objects out, request and response are local to Scriptlet and Expression. These three objects can be used by the Scriptlet and Expression straightaway. But Declaration code is placed outside the service() method of the generated Servlet. For this reason, Declaration code cannot use these three objects.

All the 9 implicit objects are created by the container in the service() method of the generated Servlet. As Scriptlet and Expression code is placed in service() method, Scriptlet and Expression can use out, request and response without any problem. But as Declaration code is placed outside the service(), the scope of request, response and out is not available to declaration.

This is very important to note in coding, else, compiler raises error.

2. Then, how to use out and request objects (which are local to service() method) from Declaration?

Redesign the calculate method like this.

Now it is correct declaration. Let us call the above method from a Scriptlet.

Now everything works fine. We are passing local out and request objects from Scriptlet to the method declaration.

This scope problem should always be taken care of by the Programmer.

Leave a Reply

Your email address will not be published. Required fields are marked *