简体   繁体   English

Thymeleaf + Spring boot - 使用getter方法显示图片

[英]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.我正在尝试通过从 thymeleaf 中的用户模型调用我的 getImageName() 来根据登录的用户动态显示图像,但我确定一些基本的东西已经错过了我,这是一个小错误,我只是看不到找到。

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();我可以通过 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.如果我将 user.getImageName() 替换为我的静态文件夹中的一张图片的名称,它会正常工作,但这样做时当然是静态的。 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 .您也可以省略@{...} ,具体取决于imageName的值。

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

(And getImageName() is equivalent to .imageName .) (并且getImageName()等效于.imageName 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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