如何在Struts 2中将QRCode图像从action类发送并显示到JSP

问题描述 投票:0回答:2

我正在提交带有字符串的 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"/>
image struts2 qr-code
2个回答
3
投票

看来您需要

<s:url
操作,您可以在
<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 中只需使用

<img src="<s:url action="image"/>" style="width:100%;"/>
。如果您需要添加路径,请在 url 中的操作和属性上使用名称空间注释。

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

这也是

ImageAction
的示例,它使用了上述所有内容和
stream
结果。


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.