JSTL/JSP EL (Expression Language) in a non JSP (standalone) context

若如初见. 提交于 2019-11-27 07:42:42

You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper.

This blog post describes how to do it: Java: using EL outside J2EE.

StringTemplate is a more lightweight alternative to Velocity and Freemarker.

I would recommend looking into Apache Velocity. It is quite simple and lightweight.

We are currently using it for our e-mail templates, and it works very well.

You can use Casper very similar to jsp and easy to use : Casper

I would go for the Spring Expression language:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html

A few examples which demonstrate the power (the first two are from the documentation):

int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context);

String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context);

// weekday is a String, e.g. "Mon", time is an int, e.g. 1400 or 900
{"Thu", "Fri"}.contains(weekday) and time matches '\d{4}'

Expressions can also use object properties:

public class Data {
    private String name; // getter and setter omitted
}

Data data = new Data();
data.setName("John Doe");

ExpressionParser p = new SpelExpressionParser();
Expression e = p.parseExpression("name == 'John Doe'");
Boolean r = (Boolean) e.getValue(data); // will return true

e = p.parseExpression("Hello " + name + ", how are you ?");
String text = e.getValue(data, String.class); // text will be "Hello John Doe, how are you ?"

You might want to look at OGNL which is the kind of library you are after. OGNL can be reasonably powerful, and is the expression language used in the WebWork web framework.

Re: Jasper and Juel being built for 1.5: And then I discovered RetroTranslator (http://retrotranslator.sourceforge.net/). Once retrotranslated, EL and Jasper works like a charm

Garth Gilmour

The idea of using EL itself outside of Java EE was advocated by Ed Burns and discussed on The Server Side. Tomcats implementation ships in a separate JAR but I don't know if it can be used outside the server.

Freemarker would do exactly what you need. This is a template engine with a syntax very similar to JSP :

http://freemarker.org/

AAh. Whereas with MessageFormat, I can do

Dear {0}. Your order will be dispatched on {1,date,EEE dd MMM yyyy}

where parameter #1 is a Date object and it gets formatted according to the pattern, there is no equivalent in EL.

In JSP, I would have used, perhaps, a format tag. In this standalone example, I am going to have to format the Date as a String in my code prior to evaluating the expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!