Home » Enterprise Java » jsp » Jsp Scriptlet Example

About Ilker Konar

Ilker Konar
I am a senior software developer with experience mostly in java-related technologies with appliance in the telecommunication industry. I have been programming for more than fifteen years. I am passionate about programming. I like learning new frameworks, languages and design patterns.

Jsp Scriptlet Example

JSP technology enables you to add dynamic content to web pages with scripting elements. In a JSP page, a Scriptlet is a block of Java code enclosed by the pair <% and %>. In this post, we will demonstrate how to use scriptlets in a web application example.

Every Java executable statements – variable declarations, manipulating Java objects, invoking the methods, catching Java exceptions… can be embedded in a JSP Scriptlet. For example, the code includes two scriptlets that let you display an HTML element or not depending on a condition:

<% if (condition) { %>
   

This is only shown if the condition is true

<% } %>

In the scriptlet elements, you can do more. For example, you can connect to a database, read a file, and get the data. Then you can handle this data, make some calculations and decide to show some certain HTML elements or how to show them. In this way, web pages gain high flexibility.

1. Overview

In the example, we create a ‘Pizza Order’ form in a JSP page with the help of scriptlets. This form takes action to forward to the other JSP page that displays the order details. Our preferred IDE is Eclipse. We use ‘Maven’ for the dependency management. We create a dynamic web application and deploy it into the Tomcat server. In one of my previous examples, I have explained how to create a Maven dynamic web application in the Eclipse, how to define a “Tomcat” server and add the application to it. You can examine: Logback Mapped Diagnostic Contexts (MDC) Example

2. JSP Code

You see the form in the Browser. The user can pick the pizza type and its size with single-selection radio buttons. If she would like to, she can add some extra toppings to the pizza using multiple-choice checkboxes. Also, the user is informed about the prices.

Pizza Order Form

Pizza Order Form

At the top of the JSP page, we add some scriptlet codes that define the data structures which keep the data in the JSP page. We create lists for pizza types and pizza toppings and add some data to them. Alternatively, you can read the data from database or files, then use and manipulate them in your JSP scriptlets. We put the lists in the Session Object after we initially create them. In the following requests, we get the list instances from the Session Object:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="com.javacodegeeks.examples.jspscriptletexample.Pizza" %>
<%@ page import="java.util.*"%>

<% 
	Object sessionObj = request.getSession().getAttribute( "pizzaTypeList" );

	List pizzaTypes = null;
	
	if ( sessionObj == null ) {
		
		pizzaTypes = new ArrayList();
		
		pizzaTypes.add( new Pizza( "Kebab", 15.23f ) );
		pizzaTypes.add( new Pizza( "Vegetarian", 11.48f ) );
		pizzaTypes.add( new Pizza( "Meat Feast", 14.05f ) );
		pizzaTypes.add( new Pizza( "Sea Food", 17.82f ) );
		
		request.getSession().setAttribute( "pizzaTypeList", pizzaTypes );
		
	} else {		
		pizzaTypes = ( List ) sessionObj;
	}
	
	sessionObj = request.getSession().getAttribute( "pizzaToppingsList" );
	
	List pizzaToppings = null;
	
	if ( sessionObj == null ) {
		
		pizzaToppings = new ArrayList();
		
		pizzaToppings.add( "Tomatoes" );
		pizzaToppings.add( "Green Onion" );
		pizzaToppings.add( "Broccoli" );
		pizzaToppings.add( "Green Peppers" );
		pizzaToppings.add( "Red Peppers" );
		pizzaToppings.add( "Mushroom" );
		pizzaToppings.add( "Ham" );
		pizzaToppings.add( "Chicken" );
		pizzaToppings.add( "Beef" );
		pizzaToppings.add( "Pepperoni" );
		pizzaToppings.add( "Salami" );
		pizzaToppings.add( "Parmesan Cheese" );
		pizzaToppings.add( "Mozzarella" );
		pizzaToppings.add( "Cheese" );
		
		request.getSession().setAttribute( "pizzaToppingsList", pizzaToppings );
		
	} else {
		pizzaToppings = ( List ) sessionObj;
	}
   ...

Pizza is the model bean class that keeps the pizza attributes:

Pizza.java

public class Pizza implements Serializable {

	private static final long	serialVersionUID	= -8549196728165055605L;

	private final String		name;

	private final float			price;

	public Pizza( final String name, final float price ) {
		this.name = name;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public float getPrice() {
		return price;
	}
}

The form section of the JSP page is shown below. In the lines of 09-15, the list items are produced in a for loop traversed in the pizza type list. With JSP scriptlet, you do not have to write all of the list items statically. If you retrieve the data to be shown, you can manipulate it in order to create and display HTML tags in a JSP page. Between the lines 30 – 56, you see the pizza extra toppings section in which the topping items are displayed with 3 columns grid form. In each column, there is a separate HTML list. At the top of the form, the size of each HTML list is calculated with division of the toppings list length by 3 and the result is stored in the sliceSize variable. We also keep the remainder of this division calculation in order to use below.

In this extra toppings section, we use two nested for loops: The outer one is for each column, the inner one is for the list items in its column. We divide the extra toppings List by there. The first part of the list is shown in the first column, the second part in the second column and the last part in the last column. If there is any remainder items after the division, we append them to the first and second lists. We design the allotment of the extra toppings items to the 3 column grid with this logic. Of course, different algorithms can be planned.

...
<%
   int sliceSize = pizzaToppings.size() / 3;
   int remainder = pizzaToppings.size() % 3;
%>
<form action="orderResult.jsp" method="POST">
	<h3>Pizza Types</h3>
	<div>
		<ul>
			<% for ( Pizza pizza : pizzaTypes ) { %>
			<li>
				<input type="radio" name="pizzaTypeOptions" value="<%=pizza.getName()%>" checked />
				<span class="pizzaType"><%=pizza.getName()%></span>
				<span class="pizzaPrice"><%=pizza.getPrice()%>$</span>
			</li>
			<% } %>
		</ul>
	</div>
	<h3>Size</h3>
	<ul>
		<li id="li_1">
			<input id="pizza_size1" type="radio" name="pizzaSizeOptions" value="Small" checked/>
			<span class="pizzaSize">Small</span>
			<input id="pizza_size2" type="radio" name="pizzaSizeOptions" value="Medium"/>
			<span class="pizzaSize">Medium ( + 2$ )</span>
			<input id="pizza_size3" type="radio" name="pizzaSizeOptions" value="Large"/>
			<span class="pizzaSize">Large ( + 3$ )</span>
		</li>
	</ul>
	<h3>Extra Toppings</h3>
	<div class="section group">
		<% for ( int j = 0; j < 3; j++ ) { %>
		<div class="col span_1_of_3">
			<ul class="ul_2">
				<% for ( int i = sliceSize * j; i < ( j + 1 ) * sliceSize; i++ ) { %>
				<li class="li_2">						
					<input type="checkbox" name="pizzaToppings" value="<%=pizzaToppings.get( i )%>"/>
					<%=pizzaToppings.get( i )%>
				</li>
				<% } 
					
				if ( j == 0 && remainder > 0 ) {
				%>	
				<li class="li_2">						
					<input type="checkbox" name="pizzaToppings" value="<%=pizzaToppings.get( pizzaToppings.size() - 2 )%>"/>
					<%=pizzaToppings.get( pizzaToppings.size() - 2 )%>
				</li>						
				<% } else if ( j == 1 && remainder > 1 ) { %>
				<li class="li_2">						
					<input type="checkbox" name="pizzaToppings" value="<%=pizzaToppings.get( pizzaToppings.size() - 1 )%>"/>
					<%=pizzaToppings.get( pizzaToppings.size() - 1 )%>
				</li>						
				<% } %>
			</ul>
		</div>
		<% } %>
	</div>	
	<h4>Each extra topping is 0.65$</h4>	
	<input type="submit" value="Order"/>				
</form>
...

Please notice that this form is submitted to the other JSP page: orderResult.jsp.

   <form action="orderResult.jsp" method="POST">

In this page, we summarize the items the user preferred in the previous form. Also we calculate the total amount and display the result:

Order Result Page

Order Result Page

orderResult.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="com.javacodegeeks.examples.jspscriptletexample.Pizza" %>
<%@ page import="java.util.*"%>

<%! 
	public String prepareOutput( final String[] toppings, final String pizzaSize, 
		final String pizzaType ) {
		
		String output = pizzaSize + " '" + pizzaType + 
			"' pizza with these extra toppings : ";
		
		for ( int i = 0; i < toppings.length; i++ ) {
			output += toppings[ i ];
			
			if ( i != toppings.length - 1 ) {
				output += ", ";
			}
		} 
		
		return output;
	}	 
%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Jsp Scriptlet Example</title>
	<link rel="stylesheet" href="./static/css/pizzaorder.css">
</head>
<body>
	<h3>Order Details</h3>
	<p><%=prepareOutput( request.getParameterValues( "pizzaToppings" ), request.getParameter( "pizzaSizeOptions" ), 
		request.getParameter( "pizzaTypeOptions" ) )%></p>
	<p>TOTAL:
	<% 
		List<Pizza> pizzaTypes = ( List<Pizza> ) request.getSession().getAttribute( "pizzaTypeList" );
		
		float price = 0f;
		
		for ( Pizza pizza : pizzaTypes ) {
			if ( pizza.getName().equals( request.getParameter( "pizzaTypeOptions" ) ) ) {
				price = pizza.getPrice();
				break;
			}
		}
			
		String size = request.getParameter( "pizzaSizeOptions" );
		
		price += size.equals( "Medium" ) ? 2f : ( size.equals( "Large" ) ? 3f : 0f );
		
		price += request.getParameterValues( "pizzaToppings" ).length * 0.65f;
		
		out.print( price );
	%>
	$ 
	</p>
</body>
</html>

We build the summary string in a method ( prepareOutput ) that we create it in the JSP declaration tag ( <%! %>) at the top of the JSP page. Then we invoke this method in line 32 with the request parameters that posted in the previous form. As you see, we can declare any method and invoke them in the JSP scriptlets.

In the next scriptlet, we calculate the total price amount. First we get the pizza type that the user select from the related request parameter. We get its price in its bean class stored in the Session. We add 2 or 3 dollars if the user prefers medium or large size, respectively. Finally, we count the extra toppings selected, multiply it by the fixed item price ( 0.65 ) and add the result to the sum. Then we output the total. Please notice that we locate the scriptlet immediately before the dollar sign ( $ ). It can be at the beginning of the JSP and we can store the result in a variable. But we prefer to locate it in the place that is displayed. You are free in the location decision of the scriptlets. But you should also take into account the code readability.

3. JSP Scriptlet Debugging

In the modern IDEs like Eclipse, you are able to debug the JSP scriptlet code. After starting the application server ( Tomcat, Weblogic, … ) in debug mode, you can toggle any breakpoint, watch the variables in the scriptlet code. You see the debugging session in the orderSession.jsp with the Eclipse.

Debugging JSP Scriptlet

Debugging JSP Scriptlet

Here is the variables section of the Eclipse Debug Perspective. You can watch variables values while debugging:

Debugging JSP Scriptlet

Debugging JSP Scriptlet

4. Download the Eclipse Project

This code demonstrates JSP scriptlets in a simple web application. Download link is below.

Download
You can download the full source code of this example here : jspScriptletExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of