Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

When developing web applications with JSP, there often arises a need to pass data from the server-side JSP to the client-side JavaScript. This allows for dynamic interactions and customization on the client side.

In this tutorial, we’ll explore different approaches to accessing a JSP variable from JavaScript.

2. Setup

Before we begin, we’ll need to set up our environment to include the JSTL library for supporting JSTL tags in our JSP pages:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

We’ll need the commons-text library to handle text manipulation, including escape Javascript statements as well:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>

3. Convert to a JavaScript Variable

Let’s start by considering a scenario where we have a JSP variable and want to embed it as a JavaScript variable:

<% 
    String jspMsg = StringEscapeUtils.escapeEcmaScript("Hello! This is Sam's page.");
    request.setAttribute("scopedMsg", jspMsg);
%>

To handle JavaScript literals properly, we utilize the StringEscapeUtils.escapeEcmaScript() method from the commons-text library for sanitization. This method helps us escape any single-quote or double-quote characters that might cause issues when we embed the variable in a JavaScript statement.

If we neglect to escape these characters, it may lead to JavaScript errors due to syntax conflicts. JavaScript treats single quotes and double quotes as special characters that can potentially disrupt the structure of a JavaScript statement. Therefore, it’s crucial to escape them to ensure the JavaScript code remains intact.

In this example, we aim to convert the JSP variable jspMsg into a JavaScript variable jsMsg, such that we can access the JSP variable on the client side:

<script type="text/javascript">
    var jsMsg = // conversion implementation here
    console.info(jsMsg);
</script>

We’d expect to see the message “Hello! This is Sam’s page.” in the browser console. Next, let’s explore the different approaches that we can apply for conversion.

3.1. Using JSP Expression Tag

The simplest way to convert a JSP variable to a JavaScript variable is by using the JSP expression tag <%= %>. We can directly embed the JSP variable within the JavaScript code:

var jsMsg = '<%=jspMsg%>';

When dealing with a scoped variable, such as one stored in the request scope, we can retrieve the attribute using the implicit request object:

var jsMsg = '<%=request.getAttribute("jspMsg")%>';

3.2. Using JSTL

JSTL can only access the scoped variable. We’ll use JSTL’s <c:out> tag to convert the scoped variable for JavaScript usage:

var jsMsg = '<c:out value="${scopedMsg}" scope="request" escapeXml="false"/>';

The scope attribute is optional but useful when dealing with duplicate variable names in different scopes. It instructs JSTL to fetch the variable from the designated scope.

If the scope isn’t specified, JSTL follows the order of page, request, session, and application scopes to fetch the scoped variable. It’s generally a good practice to explicitly specify the scope in the tag.

The escapeXml attribute controls whether the value should be escaped for XML/HTML entities or not. Since we’re converting it to JavaScript instead of HTML, we set this attribute to false.

3.3. Using JSP Expression Language (EL)

With the same scoped variable as the previous section, we could simplify the statement by using EL:

var jsMsg = '${jspName}';

We can see there’s no scope supplied in the previous statement as the simplest form. The fetch order without specifying scope is the same as what we’ve described in JSTL. We can prepend the EL implicit scope object to the variable name if we want to explicitly specify the scope:

var jsMsg = '${requestScope.jspName}';

4. Convert to HTML

Sometimes, we may want to convert a JSP variable containing HTML tags into an actual HTML tag representation that displays to users:

<% request.setAttribute("jspTag", "<h1>Hello</h1>"); %>

In this example, we’ll convert the JSP variable to HTML contents within <div> tag. We’ll use the JSP expression tag from before to display the HTML tag:

<div id="fromJspTag"><%=jspTag%></div>

Once the JSP variable has been converted to an HTML tag, we can access its content using JavaScript. We could simply access the content as a DOM element using JavaScript:

var tagContent = document.getElementById("fromJspTag").innerHTML;

5. Conclusion

In this article, we explored different techniques to access JSP variables from JavaScript. We discussed using JSP expressions, JSTL tags, and JSP Expression Language (EL) to convert and access variables.

It’s important to sanitize JSP variables before converting them to JavaScript variables. Additionally, we briefly discussed converting variables to HTML tags dynamically.

By understanding these methods, we can effectively pass data from JSP to JavaScript, enabling dynamic and interactive web application development.

As usual, all the source code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.