2
votes

Is it possible with spring expression language to extract a collection and at the same time modify a property on each object in the collection? In my example I have a list of users whose name is too lang and I would like to limit the length of the names before they are displayed in a page (so not update the original list). This code is used in a controller which is requested via ajax and the list of users is returned as a json array.

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(rankedUsers);
List<User> longNamedUsers = (List<User>) parser.parseExpression("?[name.length() > 20]").getValue(context);

EvaluationContext newContext = new StandardEvaluationContext(longNamedUsers);
// the below does not work but throws an exception
//parser.parseExpression("?[name]").setValue(newContext, "test");
2
Could you post some more information please? Are you trying to truncate the names for a displaying purpose? Are you using JSP or JSF? Does this code appear in a controller or a service? - Stefan

2 Answers

0
votes

You have some possibilities, matters what you want to achieve. To get all names, and those who are longer then a certain size shorten, you can do it this way:

List<User> lu = new ArrayList<User>();
lu.add(new User("Short user name"));
lu.add(new User("Very long user name which should be shortend"));

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(lu);

List<String> names = (List<String>)parser.parseExpression("![name.length() > 20 ? name.substring(0,20) : name]").getValue(context);

for (String name : names) {
    System.out.println("Name: " + name);
}
0
votes

Spring's EL is used to extract data from an object or graph of objects, not to mutate or set values on those objects. When you call setValue() it is on the Expression returned from the parser and not the objects from which the Expression was parsed.