可以在Java内部使用JSP模板吗? [英] Can a JSP template be used from within Java?

查看:46
本文介绍了可以在Java内部使用JSP模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JSP还是很陌生.到目前为止,似乎处理流程主要是Java首先运行,然后填充JSP模板.

I'm pretty new to JSP. So far it seems that the flow of processing is very much Java runs first, then populates a JSP template.

我想知道Java是否有一种方法可以利用JSP模板.我的意思是,想象一下我在类路径上有一个简单的"SimpleDiv.jsp"模板,如下所示:

I am wondering if there is a way from within Java to utilize a JSP template. What I mean is, imagine I had a simple "SimpleDiv.jsp" template on classpath like this:

<div id="${id}" class="${class}">
    ${content}
</div>

然后从任意Java文件(甚至可能不在servlet上运行)中,我可以执行以下操作:

And then from within an arbitrary Java file (perhaps not even running on a servlet), I could do something like this:

private String getDivHtml( id, html ) {
    Template simpleDiv = TemplateLoader.load("SimpleDiv.jsp");
    simpleDiv.set("id", id);
    simpleDiv.set("class", Whatever.CLASS_NAME);
    simpleDiv.set("content", html);

    return simpleDiv.toString();
}

这是一个非常简单的示例,因此不要被其细节所困扰.主要问题是-我可以引入Java中的JSP模板并使其生成内联HTML吗?

This is a pretty simplistic example so don't get caught up on the details of that. Main question is -- can I pull in a JSP template in Java and cause it to generate HTML inline?

推荐答案

Freemarker和Velocity在通过模板生成内容方面非常流行,您可以尝试其中一种.由于JSP被实现为Servlet(并且JSP规范将其定义为Web组件),因此它们被绑定到Servlet容器.

Freemarker and Velocity are very popular for generating content from templates, you might try one of them. Since JSPs are implemented as servlets (and the JSP spec defines them as webcomponents) they are tied to the servlet container.

这篇关于可以在Java内部使用JSP模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆