ImageShowAction.java是用于显示图片的Action,这个action先把数据库里的图片取出,用Blob类型的变量存起来,用方法Blob.getByte
(long pos,int length)取出图片的byte[]数组,最后在response对象里设置图片格式,用ServletOutPutStream输出即可。下面是示例代码:
Action中代码:
/**
* test show image in jsp
* @param ActionMapping mapping...
* @throws SQLException
* @author wjs
* @date 2008-2-3
*/
public ActionForward showImage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
int length = 0;
ServletOutputStream toClient = null;
byte[] buf=null;
CommodityService service = new CommodityService();
List list = service.getCommodityByX(null, null);
Commodity commodity = (Commodity) list.get(2);//取得商品对象
Blob image = commodity.getImage();//取得以blob格式存储图片信息
try {
//is = image.getBinaryStream();//取得二进制流
length = (int)image.length();//取得流中的可用字节总数
//buf=new byte[length];//设定字节数组长度
buf=image.getBytes(1,length);//获取Blob字节数组
response.setContentType("image/jpeg");
toClient=response.getOutputStream();//获取输出流
for (int i = 0; i < buf.length; i++) {
toClient.write(buf[i]);//输出到页面
}
toClient.close();//关闭输出流
} catch (SQLException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mapping.findForward("showImage");//跳转到指定页面
}
struts.config.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans> <form-bean name="userActionForm" type="com.mt.struts.UserActionForm" /> <form-bean name="commodityForm" type="com.mt.struts.CommodityForm" /> </form-beans> <global-exceptions /> <global-forwards> <!-- <forward name="error" path="/error.jsp" />--> </global-forwards> <action-mappings> <action attribute="userActionForm" input="/form/userAction.jsp" name="userActionForm" parameter="postMethod" path="/userAction" scope="request" type="com.mt.struts.UserAction"> <forward name="ok" path="/index.jsp" /> <forward name="login" path="/login.jsp" /> <forward name="userList" path="/back/userlist.jsp"></forward> </action> <action attribute="commodityForm" input="/form/commodity.jsp" name="commodityForm" parameter="postMethod" path="/commodityAction" scope="request" type="com.mt.struts.CommodityAction"> <forward name="goodList" path="/goodlist.jsp" /> <forward name="goodAdd" path="/back/goodadd.jsp" /> <forward name="showImage" path="/back/showimage.jsp" /> </action> </action-mappings> <message-resources parameter="com.mt.struts.ApplicationResources" /> </struts-config>
JSP页面部分代码:
<body>
This a struts page. <br>
<html:image src="/commodityAction.do?postMethod=showImage"></html:image>
</body><!--这里用的是struts标签-->
其中showImage.do在struts-config.xml中配置定义为commodityAction.java