How to use scriptlets in jsp page

The JSP scriptlets is the block of code where you can write any logic using other variable or any stuff, the code written in JSP scriptlets will go as part of service method. Inside JSP scriptlets block you can define any local variables or any logic using already declared variables in other JSP blocks.

JSP scriptlets syntax

The JSP scriptlets syntax is <% scriptlets code %>. You can define any logic using declared local variables and can put any logic using any variables or methods already which are already declared. You can define any scriptlets code inside the ‘<%' and '%>‘ block.

Example of JSP scriptlets

Below is the example of JSP scriptlets where we are declaring date format and using that we are getting the today date. Which we are giving as output is JSP page.

<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%><HTML>
 
<BODY>
<%
    // This is a scriptlet bloc of JSP.
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
    String todayDate = format.format(new Date());
%>
 
Date in format 'dd-MM-yyyy' is : <%=todayDate%>
</BODY>

The output of the above Jsp code would be like this:

how-to-use-scriptlets-in-jsp-page