MVEL2.0模板(模板集成)

MVEL 2.0 Template Integration

Using MVEL templates is straight-forward and easy. Like regular MVEL expressions, they can be executed interpretively, or be pre-compiled and be re-used for faster evaluation.

The org.mvel.templates.TemplateRuntime Class

The TemplateRuntime class is the center of the template engine. You can pass a template to be evaluated to the template engine by way of the eval() method.

In general, the template engine follows all the same rules for context and variable binding, with an overloaded set of eval() methods.

Here's a simple example of parsing a template interpretively:

String template = "Hello, my name is @{name.toUpperCase()}");
Map vars = new HashMap();
vars.put("name", "Michael");

String output = (String) TemplateRuntime.eval(template, vars);

At the end of execution, the "output" variable will contain the string:

Hello, my name is MICHAEL

The org.mvel.templates.TemplateCompiler Class

The TemplateCompiler class allows for pre-compilation of the templates.

When you compile a template, a compact, reusable evaluation tree is produced that can be quickly used to evaluate a template. It is used straightforwardly:

String template = "1 + 1 = @{1+1}";

// compile the template
CompiledTemplate compiled = TemplateCompiler.compileTemplate(template);

// execute the template
String output = (String) TemplateRuntime.execute(compiled);

At the end of execution, the "output" variable will contain the string:

1 + 1 = 2

你可能感兴趣的:(MVEL2.0模板(模板集成))