Scriplet and page directive

Informally, a JSP page is nothing more than a mix of HTML and Java. Here we are going to see how to use the JSP technology a bit more formally.

Let's say that we want that our JSP page to show the number of times it has been accessed. To do that we create an simple helper Java class in the source packages for our Web Application:
package ch07;
public class Counter {
    private static int count;

    public static synchronized int getCount() {
        return ++count;
    }
}
To use this class in a JSP we have to solve a couple of problems: how to import a class, and how to write Java code in a JSP page.

The first problem is solved by referring to the page directive: <%@page %>
The second one putting the Java code in a scriplet: <% /* ... */ %>

So, here is our simple JSP page:
<%@page import="ch07.Counter" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        The page count is: <% out.println(Counter.getCount()); %>
    </body>
</html>

More detail in the seventh chapter of Head First Servlet and JSP. I originally wrote this post while reading it.

No comments:

Post a Comment