The scriptlet tag of JSP:
Scriptlet is the main tag of JSP. It is used to add request processing logic to a JSP page. A JSP page may contain any number of scriptlet tags. It has following syntax:
At the time of translation, contents of the scriptlet tags are copied as it is to the _jspService() method of the auto generated servlet as demonstrated by the following diagram:
In the diagram, the package name & class name are not specified because they are server dependent. Usually the servlet name has the JSP name as part of it. Different server store the auto generated servlet in different folder e.g. the Tomcat server stores them in work->catalina->localhost folder.
Within a scriptlet, following implicit objects are made available to the JSP programmers i.e. they can be directly used in a scriptlet tag.
Lets understand the magic behind these implicit objects. As explained by the above diagram that the scriptlet contents are copied as it is to the _jspService() method of the auto generated servlet. In this method, these objects are declared before pasting the contents of the scriptlets. A JSP isn’t executed. It is just a means to get a servlet generated which is actually used to process requests. By this mechanism, A JSP programmer gets the illusion that he is using the objects without declaring them.
Practical example of the scriptlet tag:
First, the index.html :
<form method="post" action="adder.jsp"> First No: <input type="text" name="num1"><br/> Second No: <input type="text" name="num2"><br/> <input type="submit" value="add"> </form>
Second, the adder.jsp :
<% int a=Integer.parseInt(request.getParameter("num1")); int b=Integer.parseInt(request.getParameter("num2")); int c=a+b; out.println("sum is: "+c); %>
With the help of this example, you may have understood the simplification which is facilitated by the JSP over servlet. No class and method need to be defined, no object is declared or obtained, no content type is set, no entry is required in web.xml, no compilation is required. Only the required processing logic is written in a JSP which is used by the translator to define the request processing logic of the generated servlet.