tutorials / java-server / jsp

JSP

tutorial java server jsp

Now we know how to add servlets to our web apps. A servlet looks like this:

import java.io.PrintWriter;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>My Web App</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>My Web App</h1>");
		out.println("<p>The current time is: " + new Date().toString() + "</p>");
		out.println("</body>");
		out.println("</html>");
	}
}

This code uses the out.println() function to output HTML one line at a time. In other words, this is HTML inside Java.

There are a few problems with having HTML inside Java:

Basically, it’s just annoying to work this way.

This tutorial introduces JSP, or JavaServer Pages, which are more like Java inside HTML.

JSP Files

Instead of writing a Java program that contains HTML, JSP allows you to write HTML that contains Java code. Here’s a JSP file that outputs the same dynamic content (the current date) as the above servlet:

<%@ page import="java.util.Date" %>
<!DOCTYPE html>
<html>
	<head>
		<title>My Web App</title>
	</head>
	<body>
		<h1>My Web App</h1>
		<p>The current time is: <%= new Date().toString() %></p>
	</body>
</html>

Save this to a file named date.jsp in your web app’s directory. Your file structure should look like this:

Now open a browser to http://localhost:8080/MyWebApp/date.jsp, and you should see this:

date jsp

When you visit the .jsp file, the Jetty server automatically compiles it into a servlet class, which then works just like any other servlet. Note that this requires a Java server! So you can’t upload a .jsp file to any file host. It has to be a Java server.

But now instead of writing Java code that contains HTML, you can write HTML that contains Java code. This makes it much easier to write a webpage.

There are a few ways to include Java code in a JSP page.

Scriptlets

A scriptlet is Java code that does something and is placed between opening <% and closing %> scriptlet tags. Here’s an example:

<!DOCTYPE html>
<html>
	<head>
		<title>Coin Flipper</title>
	</head>
	<body>
		<h1>Coin Flipper</h1>
		<p>Flipping a coin...</p>
		<% if(Math.random() < .5){ %>
			<p>Heads!</p>
		<% } 
		else{ %>
			<p>Tails!</p>
		<% } %>
		<hr />
		<p>Refresh to flip again.</p>
	</body>
</html>

This code uses an if statement and the Math.random() function to show Heads! or Tails! randomly.

coin flipper jsp

Notice a couple things in the above code:

Expressions

An expression is Java code that evaluates to a value and is placed between opening <%= and closing %> expression tags. Here’s an example:

<!DOCTYPE html>
<html>
	<head>
		<title>Unix Time</title>
	</head>
	<body>
		<h1>Unix Time</h1>
		<p>The current Unix time is: <%= System.currentTimeMillis() %></p>
		<hr />
		<p>Showing number of milliseconds since midnight on January 1, 1970.</p>
		<p>Click <a href="https://en.wikipedia.org/wiki/Unix_time">here</a> for more info.</p>
	</body>
</html>

This code uses an expression to insert the value returned from the System.currentTimeMillis() function into the HTML of the page.

unix time JSP

Mixing Scriptlets and Expressions

You can use both scriptlets (code that does something) and expressions (code that evaluates to a value) in the same JSP file. Here’s a very basic example:

<% String message = "hello!"; %>
<p>Here's some HTML</p>
<p>Message: <%= message %></p>

Notice that we use a scriptlet to create a message variable. Then later on in the code, we use an epression to insert the value of that variable into the HTML.

Here’s a more complicated example:

<% String[] animals = {
	"lions", "tigers", "bears", "lizards", "zebras",
	"kangaroos", "elephants", "cows", "monkeys", "anteaters"
	}; %>
<!DOCTYPE html>
<html>
	<head>
		<title>JSP Zoo</title>
	</head>
	<body>
		<h1>JSP Zoo</h1>
		<p>Here are the animals we visited at the zoo:</p>
		<% for(int i = 0; i < animals.length; i++){ %>
			<p><%= i+1 %>: <%= animals[i] %></p>
		<% } %>
	</body>
</html>

This code uses a scriptlet to define an array named animals. Then it uses another scriptlet to iterate over that array using a for loop. Inside the for loop, it uses an expression to print the index, and the value in the array at that index. Finally, it uses another scriptlet to close the loop.

JSP zoo

Directives

So far, we’ve learned that scriptlets contain code that does something, and expressions contain code that evaluates to a value. Directives are placed between opening <%@ and closing %> tags, and they contain code that tells the page itself what to do.

Directives can contain things like Java import statements, like in the first line of this code:

<%@ page import="java.util.Date" %>
<!DOCTYPE html>
<html>
	<head>
		<title>My Web App</title>
	</head>
	<body>
		<h1>My Web App</h1>
		<p>The current time is: <%= new Date().toString() %></p>
	</body>
</html>

Directives can also be used to include content from other files. For example, we can use this to create a navigation bar in one file, and then include that file in all of our JSP pages.

Save this content to a file named header.html:

<div style="border: thin solid black; padding:5px;">
	<a href="home.jsp">Home</a>
	<a href="about.jsp">About</a>
	<a href="pictures.jsp">Pictures</a>
	<a href="help.jsp">Help</a>
</div>

Now that we have that file, we can use a directive to include that on our JSP pages:

<!DOCTYPE html>
<html>
	<head>
		<title>Header Example</title>
	</head>
	<body>
		<%@ include file = "header.html" %>
		<p>Content goes here.</p>
	</body>
</html>

The include directive inside the <body> tag copies the content from header.html into the content of the JSP file, so we see the header in our page:

JSP header include

This makes it easy to share content between multiple pages. If we had 100 pages that included the header, we would only need to change one file to change the header on every page.

Errors

Remember that JSP files are compiled into servlets automatically. That means we have to pay attention to the output, so we know when errors happen.

Let’s take this example JSP:

<!DOCTYPE html>
<html>
	<head>
		<title>Error Example</title>
	</head>
	<body>
		<% String messageOne = "hello"; %>
		<p>Message: <%= messageTwo %></p>
	</body>
</html>

This code creates a messageOne variable, but then tries to read a messageTwo variable. The messageTwo variable doesn’t exist, so this code won’t compile.

If we try to visit this page, we’ll see an error:

JSP error

This can seem overwhelming at first, but it’s actually telling you exactly what the problem is.

An error occurred at line: 8 in the jsp file: /index.jsp
messageTwo cannot be resolved to a variable
5: 	</head>
6: 	<body>
7: 		<% String messageOne = "hello"; %>
8: 		<p>Message: <%= messageTwo %></p>
9: 	</body>
10: </html>

This is telling you that the error is on line 8, and that it can’t find the messageTwo variable.

For better or worse, encountering errors like this is a natural part of programming! If you can’t figure out where an error is coming from, try to isolate the problem in a smaller example.