How to print server variables in JSP as JSON

For frontend developers usually is not very clear how server variables are injected in JSP and what data is presented in this variables. To simplify their work could be used JSTL function, which will output server variable in json format.

Firstly must be created java implementation of dumpAsJSON function in web/src/com/blog/storefront/tags/CustomFunctions.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.blog.storefront.tags;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class CustomFunctions {

    private CustomFunctions() {
    }
\

    public static String dumpProperties(Object obj) {
        return ReflectionToStringBuilder.toString(obj, ToStringStyle.MULTI_LINE_STYLE);
    }

    public static String dumpAsJSON(Object obj) {
        StringBuilder result = new StringBuilder();

        try {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            result.append(ow.writeValueAsString(obj));
        } catch (JsonProcessingException e) {
            result.append("Note:").append(e.getMessage());
        }

        return result.toString();
    }
}

As a bonus was defined dumpProperties function, which simply outputs all attributes of passed object.

Finally must be created .tld file with definition of functions web/webroot/WEB-INF/common/tld/customtags.tld:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">

    <tlib-version>1.0</tlib-version>
    <short-name>custom</short-name>
    <uri>http://hybris.com/tld/customtags</uri>

    <function>
        <name>dump</name>
        <function-class>com.blog.storefront.tags.CustomFunctions</function-class>
        <function-signature>java.lang.String dumpProperties(java.lang.Object)</function-signature>
    </function>

    <function>
        <name>dumpAsJSON</name>
        <function-class>com.blog.storefront.tags.CustomFunctions</function-class>
        <function-signature>java.lang.String dumpAsJSON(java.lang.Object)</function-signature>
    </function>

</taglib>

After this steps sample code in jsp will output product as json in html generated by server:

1
2
3
4
<%@ taglib prefix="custom" uri="http://hybris.com/tld/customtags" %>

Product info:
${custom:dumpAsJSON(product)}
comments powered by Disqus