Java 如何在Spring应用程序的html页面中添加图片
我有一个Java 如何在Spring应用程序的html页面中添加图片,java,image,spring,Java,Image,Spring,我有一个Spring应用程序,我正在使用jboss7.1.1运行我的服务器 当我单击submit时,它将转到我的控制器,该控制器从另一个java类调用方法。此方法创建图片: ... private String filePath = "./qrcode.png"; ... FileOutputStream fout = new FileOutputStream(filePath); ... 最后,图片保存在目录中: jboss-as-7.1.1.Final\bin 现在,我想在我的html页
Spring
应用程序,我正在使用jboss7.1.1
运行我的服务器
当我单击submit时,它将转到我的控制器,该控制器从另一个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
):
而不是
private String filePath = "./qrcode.png";
一切正常
在我的mvcservlet.xml中,我得到了:
<mvc:resources location="/qrcodes" mapping="/qrcodes/**" />
您可以通过上下文使用资源
类加载它:
Resource template = ctx.getResource("some/resource/path/myTemplate.png");
资源类具有类似于getURL()
,getFile()
等方法,您可以使用这些方法获取图片的路径
关于Spring资源的更多信息:您应该在哪里使用?您应该知道这一点,因为我不知道您的代码的结构,但这可以工作:model.addAttribute(“qimage”,getContext().getResource(“/qrcodes/qrcode.png”).getFile().getAbsolutePath());我认为这与你获得模型的背景相同。也许这篇文章可以帮助你:嗨,在你的链接之后,我编辑了我的控制器,但我仍然看不到我的图片。我编辑了我的帖子并添加了控制器。你能看一下吗?提前谢谢。
<mvc:resources location="/qrcodes" mapping="/qrcodes/**" />
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 template = ctx.getResource("some/resource/path/myTemplate.png");