Tutorial 4: Importing classes to use within your JSP pages

This tutorial shows how to use an external class within your JSP pages to perform complex logic.

Why import classes?
Many beginners, including myself, feel tempted to put all of our code within code blocks directly on the JSP page in scritplets. While this does work, soon your JSP files will become enormous and hard to manage. The beauty of Object Orientated languages is that you can modularise all of your code into objects and then import them into many different parts of your applications. There are a range of benefits to doing this, including limiting code reuse (you can just import and call the same object) and abstraction (you can use other peoples objects, and assuming they are well documented, you don’t necessarily have to understand the complex innerworkings of the object, but just what it requires in its methods.)

For this example, I have imported the java.util.Random class which is used to generate a random number. java.util.Random is part of the core java API and can be imported into any of your classes or JSP files where needed.

An import statement in JSP looks like this:

<%@ page import="java.util.Random" %>

1. Below is an example of using this class to create a single random number. Simply put this into your own JSP page and include the above import and you should also be able to output a random number.

<%
Random random = new Random();
int randomNumber = random.nextInt(100);
%>

One random number:<%= randomNumber %>

2. To make things a little more interesting, the below example generates 50 random numbers by using a for loop.

<%
Random random2 = new Random();

for(int i=0;i<50;i++){
	int randomNumbers = random2.nextInt(100);
	out.print(i+") "+randomNumbers+"<br>");
	
}
%>

Full source code is below to provide a little more detail on where to include the import statement in the context of a full JSP page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.Random" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test03</title>
</head>
<body>

1. below will generate ONE random number<br>


<%
Random random = new Random();
int randomNumber = random.nextInt(100);
%>

One random number:<%= randomNumber %>


<br><br>

2. below will generate FIFTY random numbers<br>

<%
Random random2 = new Random();

for(int i=0;i<50;i++){
	int randomNumbers = random2.nextInt(100);
	out.print(i+") "+randomNumbers+"<br>");
	
}
%>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *