Spring Expression Language (SpEL) is not working when hyphen is used

僤鯓⒐⒋嵵緔 提交于 2020-07-16 10:07:00

问题


I am trying to parse an expression by using Spring Expression Language.

if myVariable value is set to "first-name" (value with hyphen) then getting class.org.springframework.expression.spel.SpelParseException.

ExpressionParser parser = new SpelExpressionParser();
String parsedDynamicVariablesValue = parser.parseExpression("#" + myVariable).getValue(stdContext, String.class);

how to solve issue with the hyphen?

Reference Used:
Spring Expression Language (SpEL)


回答1:


It doesn't work that way, you are trying to parse #first-name - just like Java, you can't have hyphens in variable names.




回答2:


we can provide hyphens or dash in the expressions inside square bracket with quotes. something below like this would work.

String expressionString = "#{response.headers['header-1']}";

Eg:

    String response = "{\"response\":{\"headers\":{\"header-1\":\"header2\",\"header1\":\"header1\"},\"body\":{\"body\":\"body\"}}}";
    String expressionString = "#{response.headers['header-1']}";
    ExpressionParser parser = new SpelExpressionParser();
    DefaultConversionService conversionService = new DefaultConversionService();
    conversionService.addConverter(new Converter<JsonPropertyAccessor.ToStringFriendlyJsonNode, String>() {
        public String convert(JsonPropertyAccessor.ToStringFriendlyJsonNode source) {
            return source.toString();
        }
    });
    StandardTypeConverter standardTypeConverter = new StandardTypeConverter(conversionService);
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setTypeConverter(standardTypeConverter);

    JsonPropertyAccessor jsonPropertyAccessor = new JsonPropertyAccessor();
    context.addPropertyAccessor(jsonPropertyAccessor);
    context.setRootObject(response);

    TemplateParserContext templateParserContext = new TemplateParserContext();
    Expression expression = parser.parseExpression(expressionString, templateParserContext);
    System.out.println(expression.getValue(context));

OUTPUT: header2



来源:https://stackoverflow.com/questions/44122683/spring-expression-language-spel-is-not-working-when-hyphen-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!