How to Use JSP Scriptlet

Posted on

This article specifies on how to use JSP scriptlet inside the JSP file. It is one of the available feature which can be used in JSP. Scriptlet is basically a Java source code inserted in the JSP file as a script. Basically, JSP file has a standard tag which is used to enclose the scriptlet. The opening tag is <%  and it is followed with the scriptlet. After the scriptlet is written, it must be ended with a closing tag %>.

Below is an example of a JSP scriptlet :

Server Time : <%=new Date()%>

The above is an example of a scriptlet where the output of the above scriptlet is printing the current date based on the date in server where the JSP script is being processed.  For more elaborate example of the JSP file using scriptlet there are pre-requirements or preparations need to be taken. Those preparations are :

1. Java program installed.

Refer to the article titled ‘How to Install Java Program in Ubuntu Linux Operating System’ for an alternative reference in this link to be able to install it.

2. Setup the Java program in the environment of the operating system used.

Check the article titled ‘How to Setup Java Environment for Netbeans in Ubuntu Linux Operating System’ in this link to get the grasp of configuring Java program so it can be properly executed according to the operating system’s environment.

3. Make sure to use an IDE where in the context of this article, it is Netbeans.

Read the article titled ‘How to Install Netbeans in Ubuntu Linux operating system’ in this link to check an alternative reference on how to install in.

After all of the above preparations have been done, the next thing is plan on testing or executing the JSP file which has the scriptlet written inside. Below is the content of JSP file which is used as an example :

Document : jsp-scriptlet
Created on : May 20, 2018, 4:28:22 PM
Author : user

<%@page import=”java.util.Date”%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
String name = “Mike”;
Date date = new Date();

out.println(name +” is accessing the JSP page at “+date);

The above script is actually scriplet using a class from Java which is called ‘Date’. This class is used to print the current date retrieved from the server processing the script. Off course, like the usual Java file using a class, it must be imported first. So, below is the import line as shown in the above :

<%@page import=”java.util.Date”%>

After that, the following line extracted from the above snippet code, instantiate the class and pass it to a variable named date :

Date date = new Date();

How to Use JSP ScriptletLast but not least, it is used to print the content of the variable named date. The output is shown as follows :

How to Use JSP Scriptlet

Leave a Reply