如何在 spring Spel Evaluator 中转义 & 字符

How to escape a & character in spring Spel Evaluator

我有一个包含单个 & 的表达式,spring spel 计算器不断抛出错误 missing expected character '&'

我试过使用反斜杠和双反斜杠来转义它,但它给出了非法转义字符错误。

这是我需要解析的表达式

(#PaymentType!=null&&!(#PaymentType).toString().isEmpty()?'PaymentType:'+((#PaymentType)+' ')+'$':'')+(#ProductSearchState!=null&&!(#ProductSearchState).toString().isEmpty()?'ProductSearchState:'+((#ProductSearchState)+' ')+'$':'')+(#Manufacturer_s39s_s32Name_s32_s38_s32Address!=null&&!(#Manufacturer_s39s_s32Name_s32_s38_s32Address).toString().isEmpty()?'Manufacturer's Name & Address:'+((#Manufacturer_s39s_s32Name_s32_s38_s32Address)+' '):'')

以下是我用来解析表达式的代码。

 public static void main (String args[]) {
   String expression="(#PaymentType!=null&&!(#PaymentType).toString().isEmpty()?'PaymentType:'+((#PaymentType)+' ')+'$':'')+(#ProductSearchState!=null&&!(#ProductSearchState).toString().isEmpty()?'ProductSearchState:'+((#ProductSearchState)+' ')+'$':'')+(#Manufacturer_s39s_s32Name_s32_s38_s32Address!=null&&!(#Manufacturer_s39s_s32Name_s32_s38_s32Address).toString().isEmpty()?'Manufacturer's Name & Address:'+((#Manufacturer_s39s_s32Name_s32_s38_s32Address)+' '):'')";
   String g = expression;
   System.out.println(g);
        final Set<String> dependent = new HashSet<>();
        try {
            ExpressionParser parser = new SpelExpressionParser();

//        log.info("Extracting dependent attributes for {} ", expression);

            new SplExpressionVisitor<Void>() {
                public void visit(SpelExpression expression) {
                    visitNode(expression.getAST());
                }

                @Override
                protected Void visit(VariableReference node) {
                    final String variableReferenceName = getVariableReferenceName(node);
                    dependent.add(variableReferenceName);
                    return super.visit(node);
                }

            }.visit((SpelExpression) parser.parseExpression(expression));

        }catch (Exception e){
            System.out.println(e.toString());
        }
    }

您的字符串 'Manufacturer's Name & Address:' 看起来像字符串 'Manufacturer' 后跟一些废话,因为您不能同时使用单引号来分隔字符串和字符串内部。

您需要在字符串中使用两个单引号字符对其进行转义,例如:

'Manufacturer''s Name & Address:'

有关在表达式中包含文字的更多信息,请参阅 SpEL 语言参考文档的“Literal Expressions”部分。