简体   繁体   中英

Thymeleaf + Spring boot - use getter method to display image

I'm trying to display images dynamically depending on which user is logged in by calling the my getImageName() from my user model in thymeleaf, but im certain that some basic stuff has missed me and its a minor error I just can't seem to find.

My controller looks like:

@GetMapping("/myProfile")
public String myProfile(HttpServletRequest request, Model model){
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");
    model.addAttribute("userToDisplay", user);
    System.out.println("Printing from myProfile "+ user.getBio());
    if(user!=null){
        return "myProfile";
    } else{
        return "redirect:/";
    }
}

I can easily print out the name of the image by user.getImageName(); My thymeleaf code line looks like:

<img th:src="@{user.getImageName()}"/>

If i replace the user.getImageName() with the name of one picture inside my static folder, it works as it should, but is of course static when doing so. All images is in static folder to statisfy folder hierachy.

Does any one know what I am actually doing wrongfully here? All I've been able to read on the internet is people using a variable from their model where mine is private. I hope someone can help me here.

Hope you have a great day! Best regards.

Without knowing what the error is... one thing that is incorrect is the way you are using variables in your @{...} expression. If you want to use a variable expression , the correct way is:

<img th:src="@{${user.imageName}}"/>

You can also just omit the @{...} , depending on the value of imageName .

<img th:src="${user.imageName}"/>

(And getImageName() is equivalent to .imageName .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM