在AJAX中使用Struts2生成图片显示在浏览器里:
1. 创建BufferedImage并在它上面进行绘制.
2. 取得response的output stream,然后使用ImageIO写入图片数据.
3. 关闭output stream,这样图片就会发送到浏览器端.
4. <img src="pic.action">: 设置img的src为Struts2里面action的名字即可.
---------------------------------- strust.xml配置 -------------------------
<package name="stuts-test" extends="struts-default" namespace="/">
<action name="pic" class="action.PictureAction" method="createPicture"></action>
</package>
----------------------------------服务器端代码:PictureAction.java -------------------------
package action;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class PictureAction extends ActionSupport {
public void createPicture() throws Exception {
BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillOval(50, 50, 100, 100);
ServletActionContext.getResponse().setContentType("image/png");
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
ImageIO.write(image, "png", out);
out.close();
}
}
----------------------------------浏览器端网页代码:pic.html --------------------------------
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Title</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#ajaxImg").attr("src", "pic.action");
});
</script>
</head>
<body>
<img id="ajaxImg" />
</body>
</html>