How to disable scripting elements in JSP pages?

With the introduction of Expression Language in JSP 2.0 it is recommended to use the EL instead of using a scripting elements / scriptlets. That means if we want to access a server-side objects it is recommended to use EL then to write some Java codes in the JSP pages.

For this purpose in JSP 2.0 we are given a feature to disable the scripting elements by defining a scripting-invalid element within the <jsp-property-group> in the deployment descriptor (web.xml) file.

Here is the JSP configuration that you need to add in the web.xml file:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>JSP Examples</display-name>

    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <scripting-invalid>true</scripting-invalid>
        </jsp-property-group>
    </jsp-config>
</web-app>

When you try to request a JSP page that have a scripting elements in, it will give you an error message like this:

HTTP Status 500 - /sessionWriteRead.jsp (line: 10, column: 2) Scripting elements ( <%!, <jsp:declaration, <%=, <jsp:expression, <%, <jsp:scriptlet ) are disallowed here.

How do I add comment in JSP pages?

In this example you’ll see how to add comments in JSP page / JSP scriptlets. To add comments we can use either the JSP comment style or HTML comment style. The different between this is that the HTML comment will be sent or included in the webpage while the JSP comment is not included in the webpage.

The JSP comment style start with the <%-- and end with the --%>. To create an HTML comment style we can use the <!-- and closed by the -->. Beside this two comment styles you can still use the comment block that we use in our Java code in the JSP scriptlets.

<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Commenting JSP Page</title>
</head>
<body>

<%--The JSP snippet below is used to print the current date--%>
<%
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
%>

<%= "Today is: " + formatter.format(date) %>
</body>
</html>

What are the scripting elements in JSP page?

There are three types of scripting elements available when writing a JSP page. These scripting elements includes:

  • Scriptlets which is a block of Java code.
  • Expression that can be evaluated and the result is printed out.
  • Declarations can be used to declares variables or methods.

Scriptlets

A scriptlets is a block of Java code that begins with <% and closed by %>. We can have multiple block of scriptlets inside a JSP page. The following example show you how to write a scriptlets:

<%@ page import="java.text.DateFormat" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Scripting Scriptlets</title>
</head>
<body>
<%
    DateFormat formatter = new SimpleDateFormat("EEE, dd/MM/yyyy HH:mm:ss");
    out.print(formatter.format(new Date()));
%>
<br/>
<%
    Calendar calendar = Calendar.getInstance();
    out.print(formatter.format(calendar.getTime()));
%>
</body>
</html>

In the scriptlets above we can use the formatter object on the first scriplet to be used in the second scriptlet. Any objects or variables declared in the first scriptlet is available on the second scriptlet.

Expression

To create an expression in JSP we can use the <%= and closed by the %>. The expression in this kind of block will be evaluated and the value is printed out as the JSP page output. We can say that the expression block is a shortcut for the out.print() method in JSP page. You also notice that an expression doesn’t end with a semicolon.

Here is an example of expression in JSP page:

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Scripting Expressions</title>
</head>
<body>
Today is: <%= new Date() %><br/>
Session Id: <%= session.getId() %><br/>

<%--The above expression is equals with the following scriptlets--%>

Today is: <% out.print(new Date()); %><br/>
Session Id: <% out.print(session.getId()); %>
</body>
</html>

Declarations

The last scripting elements is this declarations. The declarations elements starts with a <%! and ends with %>. We can use this block to declare variables and methods that can be used in a JSP page. Let’s see an example below:

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<%!
    public int add(int number1, int number2) {
        return number1 + number2;
    }

    public Date getDate() {
        return new Date();
    }
%>
<html>
<head>
    <title>JSP Declarations</title>
</head>
<body>
Today is: <%= getDate() %><br/>
20 + 10 = <%= add(20, 10) %>
</body>
</html>

How do I write and read object from HTTP Session?

In this post you will learn how to write and read object from HTTP Session in JavaServer Page. The first example that we are looking at is using the classic JSP scriptlet, this is a very old way to work with JSP, but it is good for you to know a history. We write a JSP scriptlet inside the <% %> symbols. We can use the provided session object. To set an attribute in the session object we use the setAttribute(String name, Object value) method. In the example we create an attribute called loginDate and set the value to the current date.

To read a value from a session object we use the getAttribute(String name) method. This method return a type of Object, so we need to cast it to the original object. In this case we cast it to a java.util.Date. And then we print out the value read from the session object.

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Session Write</title>
</head>
<body>
<%
// Creates a session attribute named login-date to store a java.util.Date.
session.setAttribute("loginDate", new Date());

// Read back the java.util.Date object from the session attribute.
Date loginDate = (Date) session.getAttribute("loginDate");
%>
Login Date: <%= loginDate %>
</body>
</html>

The second way that you can use to read values from session object is using the JSP Expression Language (EL). It looks like the following code snippet. You can use the sessionScope implicit object combined with the session attribute name. You can see two ways to use the sessionScope object below. The simplest one is to use the attribute name as the EL expression, and it will look smartly to find the value in the available scope.

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Session Read EL</title>
</head>
<body>
<p>Login Date: ${sessionScope.loginDate}</p>

<p>Login Date: ${sessionScope["loginDate"]}</p>

<p>Login Date: ${loginDate}</p>
</body>
</html>

How do I include a page fragment into JSP?

In this example you can learn how to include a JSP fragment into another JSP page. This is a common practice when creating a web application where we usually have a navigation section, the main content and the footer of a web page. Using the include directive make it simpler to maintain the fragment of a web page, which mean that when we need to change for example the footer section we just need to alter the footer include file and all the page that includes it will get the benefit.

The page inclusion that using the include direction will occur at page translation time, it is when the JSP page is translated into a Servlet by JSP container. We can use any file extension name for the JSP fragment used by the include directive. In this example we use the .jspf extension which is short for JSP Fragment.

Here is an example of JSP with include directive.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Include Directive</title>
</head>
<body>

<div id="header">
    <%@ include file="/include/common/header.jspf" %>
</div>

<div id="content">
    Main application content goes here!
</div>

<div id="footer">
    <%@ include file="/include/common/footer.jspf" %>
</div>

</body>
</html>

header.jspf fragment.

Header
<hr/>

footer.jspf fragment.

<hr/>
Footer