Jon*_*Jon 3 java jstl el mvel ognl
我是Java的新手。
我的目的是在Java程序中使用类似于句子的模板(没有JSP或任何与Web相关的页面)
例:
String name = "Jon";
"#{ name } invited you";
or
String user.name = "Jon";
"#{ user.name } invited you";
Run Code Online (Sandbox Code Playgroud)
如果我将此字符串传递给某种方法,我应该得到
"Jon invited you"
Run Code Online (Sandbox Code Playgroud)
我已经看过一些表达语言MVEL,OGNL,JSTL EL
在MVEL和OGNL中,我必须编写一些代码集来实现此目的,但是要采用其他方式。
我只能在JSP文件中而不是在Java程序中使用JSTL EL来实现此目的。
有什么办法可以做到这一点?
提前致谢。
乔恩
有什么办法可以做到这一点?
我不是100%肯定我了解您的要求,但是这里有一些提示...
看一下MessageFormatAPI 中的类。您可能也对Formatter类和/或String.format方法感兴趣。
如果您有一些Properties想要搜索和替换形状的子字符串,#{ property.key }也可以像这样:
import java.util.Properties;
import java.util.regex.*;
class Test {
public static String process(String template, Properties props) {
Matcher m = Pattern.compile("#\\{(.*?)\\}").matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find())
m.appendReplacement(sb, props.getProperty(m.group(1).trim()));
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
Properties props = new Properties();
props.put("user.name", "Jon");
props.put("user.email", "jon.doe@example.com");
String template = "Name: #{ user.name }, email: #{ user.email }";
// Prints "Name: Jon, email: jon.doe@example.com"
System.out.println(process(template, props));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有实际的POJO而不是Properties对象,则可以进行反射,如下所示:
import java.util.regex.*;
class User {
String name;
String email;
}
class Test {
public static String process(String template, User user) throws Exception {
Matcher m = Pattern.compile("#\\{(.*?)\\}").matcher(template);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String fieldId = m.group(1).trim();
Object val = User.class.getDeclaredField(fieldId).get(user);
m.appendReplacement(sb, String.valueOf(val));
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) throws Exception {
User user = new User();
user.name = "Jon";
user.email = "jon.doe@example.com";
String template = "Name: #{ name }, email: #{ email }";
System.out.println(process(template, user));
}
}
Run Code Online (Sandbox Code Playgroud)
...但是它越来越难看,我建议您考虑更深入地研究一些第三方库来解决这个问题。
| 归档时间: |
|
| 查看次数: |
590 次 |
| 最近记录: |