当我输入地址栏时:http://localhost:8080/greeting?name=john
我知道: EL1007E:属性或字段'john‘在null上找不到
当我将String message = (String) exp.getValue();
更改为String message = (String) exp.toString();
时,我注意到得到了正确的输出
这一切为什么要发生?我使用getValue()错误吗?
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
ExpressionParser parser = new SpelExpressionParser();
@GetMapping("/greeting")
public @ResponseBody Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
Expression exp = parser.parseExpression(name);
String message = (String) exp.getValue();
System.out.println(message);
return new Greeting(counter.incrementAndGet(), String.format(template, message));
}
@GetMapping("/number/{id}")
public Greeting number(@PathVariable int id) {
int[] myArray = {897, 56, 78, 90, 12, 123, 75};
String message = "Element in the given index is :: "+myArray[id];
System.out.println(message);
return new Greeting(counter.incrementAndGet(), String.format(template, message));
}
}
发布于 2021-09-09 05:50:11
Expression exp = parser.parseExpression(name);
String message = (String) exp.getValue();
这是不起作用的,因为在您的示例中,最终的parseExpression
将与此parser.parseExpression(john)
类似,在计算表达式时,spring将尝试在您没有提供的计算上下文中找到名为john
的属性,并且由于它没有找到任何名为john
的属性,因此会抛出一个异常。
解决方案
Expression exp = parser.parseExpression("'"+name+"'");
String message = (String) exp.getValue(new User());
public static class User {
public String john = "Value of john property";
}
上面的代码将检查给定的john
类对象中的User
属性,当它被找到时,它将返回属性的值。
john
,您可以按以下方式编写修改代码(这没有任何意义,但您可以实现它) Expression exp = parser.parseExpression("'"+name+"'"); // parser.parseExpression("'john'");
String message = (String) exp.getValue();
您可以在SpEL表达式这里上面阅读更多内容。
https://stackoverflow.com/questions/69112635
复制相似问题