簡體   English   中英

如何在Spring應用程序的html頁面中添加圖片

[英]How to add a picture in html page in Spring application

我有一個Spring應用程序,並且正在使用JBoss 7.1.1運行服務器。

當我單擊提交時,它將轉到我的控制器,該控制器從另一個Java類調用方法。 此方法創建圖片:

...
private String filePath = "./qrcode.png";
...
FileOutputStream fout = new FileOutputStream(filePath);
...

最后,圖片保存在目錄中:

jboss-as-7.1.1.Final\bin

現在,我想在我的html頁面中顯示此圖像。 在控制器中,我添加了:

model.addAttribute("qrimage", "/qrcodes/qrcode.png");

在我有的html代碼中(我使用thymeleaf ):

<td style="text-align: center">
    <img th:attr="src=@{${qrimage}} , title=#{background}, alt=#{background}" style="width: 150px; height: 150px;" />
</td>

當我訪問我的頁面時,我看到: ??background_fr?? 而不是我的照片。 當我在java類中使用時:

private String filePath = "./../standalone/deployments/myproject-web.war/qrcode.png";

代替

private String filePath = "./qrcode.png";

一切正常。

在我的mvc-servlet.xml我得到了:

<mvc:resources location="/qrcodes" mapping="/qrcodes/**" />

我想避免在我的代碼中使用硬編碼路徑 ,例如./../standalone/deployments/myproject-web.war/qrcode.png

有人可以幫我嗎?


編輯后的控制器:

package com.my.package.controller;

import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.my.package.smsgenerator.QrCodeGenerator;

@Controller
public class QrCodeGeneratorController extends AbstractController implements
        ApplicationContextAware {

    ApplicationContext applicationContext = null;

    @RequestMapping(method = RequestMethod.GET, value = "/qrcode")
    public String getPage(Model m,
            @ModelAttribute("subscription") final QrCodeGenerator subscription) {
        return "qrcode";
    }

    @RequestMapping(value = "/subscribeth", params = { "save" })
    public String save(final QrCodeGenerator subscription,
            final BindingResult bindingResult, final ModelMap model)
            throws IOException {

        subscription.buildQRCCode();

        model.addAttribute("qrimage", applicationContext.getResource("/qrcodes/qrcode.png").getFile().getAbsolutePath());

        return "forward:/qrcode";
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx)
            throws BeansException {
        this.applicationContext = ctx;

    }

}

您可以通過上下文使用Resource類加載它:

Resource template = ctx.getResource("some/resource/path/myTemplate.png");

資源類具有諸如getURL()getFile()等方法,可用於獲取圖片的路徑。

有關Spring資源的更多信息: http : //docs.spring.io/spring/docs/2.5.5/reference/resources.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM