adam bien's blog

Using MicroProfile Config to Render Web Components on the Server with JSP 📎

To inject dynamic content to *.js files on the server side, the JSP's (Jakarta Server Pages) file extension has to be configured in web.xml:


<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.js</url-pattern>
            <page-encoding>UTF-8</page-encoding>
            <default-content-type>text/javascript</default-content-type>
        </jsp-property-group>
    </jsp-config>
</web-app>

Now a String array exposed from a CDI bean:


import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.microprofile.config.inject.ConfigProperty;

@Named
@ApplicationScoped
public class Developer {

    @Inject
    @ConfigProperty(name = "languages")
    String languages;

    public String getLanguages() {
        return languages;
    }
}

...and configured in microprofile-config.properties:


languages=jsp,javascript,java    

...can be directly used to generate e.g. Web Components / Custom Elements:


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

class Languages extends HTMLElement{

        connectedCallback() {
        this.innerHTML = `
            <select>
                <c:forEach items="${developer.languages}" var="language">
                    <option>${language}</option>
                </c:forEach>
            </select>`;

    }
}
customElements.define('a-languages',Languages);    

See it in action and from scratch:

The 4kB ThinWAR project was created with Jakarta EE Essentials Archetype and deployed with: wad.sh in 2.4s