How to fix Spring Application error EL1007E: Property or field ‘john’ cannot be found on null

When I type in the URL bar: http://localhost:8080/greeting?name=john

I get this: EL1007E: Property or field ‘john’ cannot be found on null

I noticed that I get the correct output when I changed String message = (String) exp.getValue(); to String message = (String) exp.toString();

Why does this happen? Am I using getValue() wrong?

@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));
    }
    
}

Answer

Expression exp = parser.parseExpression(name);
String message = (String) exp.getValue();

This is not working because in your case the final parseExpression will be like this parser.parseExpression(john) and while evaluating this expression spring will try to find the property named john in the evaluation context which you have not provided, and as it does not found any property named john it throws an exception.

Solution

  • If you are receiving some property name in controller and that property exists in some class’s object, and you want to get the value of that property you can write your code as below.
  Expression exp = parser.parseExpression("'"+name+"'");
  String message = (String) exp.getValue(new User());

  public static class User {
    public String john = "Value of john property";
  }

above code will check for john property in given User class object, and as it is found it will return value of the property

  • If you are just trying to get the same value john by evaluation the expression you can write modify your code as below (this does not make any sense, but you can implement it)
 Expression exp = parser.parseExpression("'"+name+"'"); // parser.parseExpression("'john'");
 String message = (String) exp.getValue();

you can read more above SpEL expression here