【问题标题】:How to send and display QRCode image from action class to JSP in Struts 2如何在 Struts 2 中将 QRCode 图像从动作类发送和显示到 JSP
【发布时间】:2014-04-16 03:36:26
【问题描述】:

我正在提交一个带有字符串的 JSP 表单,并且在提交时我正在调用一个 Struts 2 操作。在该操作中,我正在使用 QRGen 库创建一个 QRCode 图像,如下所示

File QRImg=QRCode.from("submitted String").to(ImageType.PNG).withSize(100, 100).file();

我的 JSP 表单:

<form action="createQR">
Enter Your Name<input type="text" name="userName"/><br/>
<input type="submit" value="Create QRCode"/>
</form>

我的动作映射struts.xml

<action name="createQR" class="CreateQRAction">
 <result name="success">displayQR.jsp</result>
</action>

我的动作类:

import java.io.File;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;  
import com.opensymphony.xwork2.ActionSupport;
public class CreateQRAction extends ActionSupport{
 private File QRImg;
 Private String userName;

 public String execute() {
   QRImg=QRCode.from(userName).to(ImageType.PNG).withSize(100, 100).file();
return SUCCESS;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}
public File getQRImg() {
    return QRImg;
}

public void setQRImg(File QRImg) {
    this.QRImg = QRImg;
}
}

现在如果结果是成功的,我想在我的 JSP 上显示这个图像。

<s:property value="QRImg"/>

【问题讨论】:

  • 首先,显示带有 img 标签的图像。其次,您可以将其从文件中返回,或者作为原始字节。
  • 你知道图片存放的路径吗?

标签: java image jsp struts2 qr-code


【解决方案1】:

看来您需要 &lt;s:url 中的操作,您可以在 &lt;img 标记中替换为 href 属性来检索图像,类似于使用 /images 文件夹中的静态图像。

我们称之为ImageAction。这是一个写入响应的简单操作。要使用它,您需要将带有图像的文件放入会话中。因为图像是由单独的线程检索的。在execute方法中写

@Action(value = "image",  interceptorRefs = @InterceptorRef("basicStack"))
public class ImageAction extends ActionSupport {

public String execute() {

从会话中获取文件

File file = session.get("file");

那么你需要读取文件

FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[fis.available()];
fis.read(data);
fis.close();

然后把响应写出来

response.setContentType("image/png");

BufferedImage bi;
OutputStream os = response.getOutputStream();
bi = ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(bi, "PNG", os);
os.flush();

并返回 NONE 结果,因为此操作仅写入响应

return NONE;
}

完成

然后在从您的操作转发的 JSP 中,只需使用 &lt;img src="&lt;s:url action="image"/&gt;" style="width:100%;"/&gt;。如果您需要添加路径,请在 url 中的操作和属性上使用命名空间注释。

我觉得您对 Struts2 中的会话概念很熟悉,即如何将会话注入到您的操作中并在其中映射对象。在返回结果之前在您的操作中映射文件对象。

祝你好运。

【讨论】:

  • Struts2 有stream 发送原始数据的结果。
【解决方案2】:

您需要在 struts2 中使用“org.apache.struts2.dispatcher.StreamResult”。基本上在您的操作中读取图像并填充 InputStream。还设置正确配置“流”结果所需的其他变量。在动作映射中使用这些属性配置结果,该结果将是“流”类型

【讨论】:

    猜你喜欢
    • 2012-01-09
    • 2012-05-17
    • 2015-04-03
    • 2013-12-07
    • 2013-03-17
    • 2011-03-21
    • 2014-12-14
    • 2012-04-20
    相关资源
    最近更新 更多