Java写一个模版参数替换 基于el表达式的 工具类
时间: 2024-02-09 18:10:47 浏览: 140
好的,以下是一个基于 EL 表达式的模板参数替换工具类的示例:
```java
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.servlet.jsp.el.ELException;
import java.util.Map;
public class TemplateUtils {
/**
* 使用 EL 表达式替换模板参数
*
* @param template 模板字符串,例如:"Hello ${name}!"
* @param params 参数映射表,例如:Map.of("name", "World")
* @return 替换后的字符串,例如:"Hello World!"
*/
public static String replace(String template, Map<String, Object> params) {
ExpressionFactory factory = ExpressionFactory.newInstance();
ELContext context = new MapELContext(params);
ValueExpression expression = factory.createValueExpression(context, template, String.class);
try {
return (String) expression.getValue(context);
} catch (ELException e) {
throw new RuntimeException("Failed to replace template parameters", e);
}
}
/**
* 实现 ELContext 接口,将参数映射表作为变量上下文
*/
private static class MapELContext extends ELContext {
private final Map<String, Object> variables;
public MapELContext(Map<String, Object> variables) {
this.variables = variables;
}
@Override
public Map<String, Object> getVariableMapper() {
throw new UnsupportedOperationException();
}
@Override
public FunctionMapper getFunctionMapper() {
throw new UnsupportedOperationException();
}
@Override
public VariableResolver getVariableResolver() {
return new VariableResolver() {
@Override
public Object resolveVariable(String name) {
return variables.get(name);
}
};
}
@Override
public ELResolver getELResolver() {
throw new UnsupportedOperationException();
}
}
}
```
使用示例:
```java
String template = "Hello ${name}!";
Map<String, Object> params = Map.of("name", "World");
String result = TemplateUtils.replace(template, params);
System.out.println(result); // 输出:Hello World!
```
需要注意的是,这里使用了 `javax.el` 包中的一些类和接口,需要在项目中添加对应的依赖,例如:
```xml
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b09</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
```
另外,EL 表达式的语法与 JSP 中的语法相同,可参考 JSP 相关文档进行学习。
阅读全文