Programming Tutorials

Scriptlets in JSP

By: aathishankaran in JSP Tutorials on 2007-02-10  

In your first JSP program we had seen how to embed Java expressions in JSP pages by putting them between the <%= and %> character sequences. But it is difficult to do much programming just by putting Java expressions inside HTML.

JSP also allows you to write blocks of Java code inside the JSP code. You do this by placing your Java code between <% and %> characters (just like expressions, but without the = sign at the start of the sequence.)

This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any HTML (though it can, as we will see down below.) A scriptlet contains Java code that is executed every time the JSP is invoked.

Here is a modified version of our JSP from previous article, adding in a scriptlet.

<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>

Hello! The time is now <%= date %> </BODY>
</HTML>

If you run the above example, you will notice the output from the "System.out.println" on the server log. This is a convenient way to do simple debugging (some servers also have techniques of debugging the JSP in the IDE. See your server's documentation to see if it offers such a technique.)

A scriptlet does not generate HTML. But a scriptlet can generate html. If a scriptlet wants to generate HTML, it can use a variable called "out". This variable does not need to be declared. It is already predefined for scriptlets, along with some other variables. The following example shows how the scriptlet can generate HTML output.

<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>

Here, instead of using an expression, we are generating the HTML directly by printing to the "out" variable. The "out" is used for printing in the HTML page. The "out" variable is of type javax.servlet.jsp.JspWriter.

Another very useful pre-defined variable is "request". It is of type javax.servlet.http.HttpServletRequest






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JSP )

Latest Articles (in JSP)