Hi, engineers. When I use thymeleaf, I intend to use variables as keys in the map to obtain value, but by default, it seems to use variable names as strings.

The key source code is as follows:

class Node {
    public Map<String, String> mapStr;
    public String s1;
    {
        mapStr = new HashMap<>();
        mapStr.put("1", "1");
        mapStr.put("s1", "s1");
        s1 = "1";
    }
}
SpelExpressionParser parser = new SpelExpressionParser();
System.out.println("mapStr===>" + parser.parseExpression("mapStr").getValue(new Node(), Map.class));
System.out.println("s1===>" + parser.parseExpression("s1").getValue(new Node(), String.class));
System.out.println("mapStr[s1]===>" + parser.parseExpression("mapStr[s1]").getValue(new Node(), String.class));
System.out.println("mapStr[''+s1]===>" + parser.parseExpression("mapStr[''+s1]").getValue(new Node(), String.class));

The output results are as follows:

mapStr===>{1=1, s1=s1}
s1===>1
mapStr[s1]===>s1    //In my opinion, the result here should be 1
mapStr[''+s1]===>1

How to deal with this situation? It has bothered me for a week

Comment From: akuma8

mapStr[s1]===>s1 //In my opinion, the result here should be 1

Why it should be 1 since you have mapStr.put("s1", "s1")?

Comment From: liuhanguang123

mapStr[s1]===>s1 //In my opinion, the result here should be 1

Why it should be 1 since you have mapStr.put("s1", "s1")?

Just look at the variables contained in the class Node provided above 1. We think mapStr['s1']===>s1is correct because it indicates that the key is a string; 2. After testing, it is found that mapStr ['' + s1] will be converted into mapStr ['1'] to calculate the result; The calculation result of mapStr [s1] is equivalent to mapStr ['s1'] 3. I think mapStr[s1]===>s1 is wrong because its key is a variable and s1 = '1'. It should be the result of calculating mapStr['1']. The final result should be '1' instead of 's1';

Comment From: liuhanguang123

When I was testing the source code at the break point, I found a place for special processing. In class org.springframework.expression.spel.ast.Indexer search SPR-5847, and the special processing code is below the search results. After testing, if the following if statement is commented out, the result will be as I thought. From here, I found that another issue #10516 contains this problem, so my problem is unnecessary. I will close it. Thank you.