Search code examples
javahtmlimagethymeleafparse4j

Thymeleaf image src + ParseException: Exception evaluating SpringEL expression: "currentUser.get('profilePicture').get('url')"


I get a currentUser from my ApplicationAdvice class and present it on every page if the user is logged in:

@ModelAttribute("currentUser")
public TmtUser currentUser(Model model) {

    TmtUser currentUser = TmtUser.currentUser;
    model.addAttribute("currentUser", currentUser);

    return currentUser;
}

The currentUser object has a url attribute available to it. But I'm getting an error rendering the url to the page. Maybe the DOM is rendered before the url value is provided? How would I know?

HTML:

<img th:src="${currentUser.get('profilePicture').get('url')}" src="" />

Exception:

Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "currentUser.get('profilePicture').get('url')" (template: "fragments/header" - line 72, col 139)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393) ~[attoparser-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257) ~[attoparser-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230) ~[thymeleaf-3.0.3.RELEASE.jar:3.0.3.RELEASE]
    ... 105 common frames omitted

Object Model:

enter image description here

Browser Console Error:

org.parse4j.ParseFile@190687b3 Failed to load resource: the server responded with a status of 404 ()

Seems like the ParseFile itself isn't loading in the browser.


Solution

  • What do you think this expression means?

    currentUser.get('profilePicture').get('url')
    

    Does the currentUser object have a method that looks something like this?

    public class TmtUser {
        public Map<String, Object> get(String key) {
            ...
            ...
        }
    }
    

    because that is what it looks like you're trying to do. But according to the picture of your object, there is nothing like that. When you craft these expressions, you need to think about how it would look in java. For example, in java it might look like this:

    currentUser.getData().get("profilePicture").getUrl()
    

    Translated to an expression, it would look like:

    ${currentUser.data['profilePicture'].url}
    or
    ${currentUser.data.get('profilePicture').url}
    

    (With the caviat that I'm not familiar with a ParseFile, so I'm not sure if it has a getting and setter for the url property)