Как добавить картинку в html-страницу в приложении Spring

1

У меня есть приложение 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;

    }

}
Теги:
spring
image

1 ответ

2
Лучший ответ

Вы можете загрузить его с помощью класса 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

  • 0
    В каком месте я должен использовать?
  • 1
    Вы должны знать это, потому что я не знаю структуру вашего кода, но это может сработать: model.addAttribute ("qrimage", getContext (). GetResource ("/ qrcodes / qrcode.png"). GetFile (). getAbsolutePath ());
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню