Lenik
Lenik

Reputation: 14458

How to programmatic render JSP files?

Currently, I'm using Velocity instead of JSP, for its flexibility. For some reasons, I need to distribute my web modules in jar archive, rather than war archive`.

I have read the servlet specification, though, but I didn't find a way to programmatic invoke the jasper engine.

My idea is, split web application to several modules:

It's very easy to embed Velocity templates in class resources, so I'm wondering if I can do the same job with JSP?

EDIT

The problem of Velocity is, we have to use some taglibs, JSF, etc. to create a rich web UI, which can't be done by Velocity templates.

Upvotes: 2

Views: 458

Answers (1)

BalusC
BalusC

Reputation: 1109625

we have to use some taglibs, JSF, etc. to create a rich web UI, which can't be done by Velocity templates.

Use Facelets instead of JSP. It not only offers better templating possibilities than JSP, but it is also possible to serve Facelet files straight from classpath. Assuming that you're still on JSF 1.x (because JSF 2.x uses by default Facelets instead of JSP and there is really no reason to prefer JSP over Facelets), then you can enable serving Facelets from JAR as follows:

import com.sun.facelets.impl.DefaultResourceResolver;

public class CustomResourceResolver extends DefaultResourceResolver {

    @Override
    public URL resolveUrl(String resource) {
        URL url = super.resolveUrl(resource);

        if (url == null) {
            if (resource.startsWith("/")) {
                resource = resource.substring(1);
            }

            url = Thread.currentThread().getContextClassLoader().getResource(resource);
        }

        return url;
    }

}

which you register as follows in web.xml:

<context-param>
    <param-name>facelets.RESOURCE_RESOLVER</param-name>
    <param-value>com.example.CustomResourceResolver</param-value>
</context-param>

To learn more about Facelets, start with this excellent developer documentation.

Upvotes: 1

Related Questions