jsp用源从数据库读取图片, 如果有图片就显示,没有则显示默认的图片

jsp用流从数据库读取图片, 如果有图片就显示,没有则显示默认的图片
[size=medium]数据库中存放的头像是byte[] 字节的,在jsp页面上根据用户的id用流从数据库中读取图片。但是如果用户没有头像的话,那么在页面上显示的就是一个图片的小白框框,难看死了,所以如果用户没有头像的话,就给用户一个默认的头像。
在User类中:
private byte img[];

在UserAction类中:
ClientUser user = new ClientUser();
user=UserService.getUserByUserId(sqlSession,user);				request.getSession().setAttribute("LoginUserImg", user.getImg().length);
//在这里需要用byte[]对象的length属性判断是否存放了图片,如果length为0,那么就没有图片,反之则有。

在jsp页面中:
<c:if test="${LoginUserImg==0 }">
					<img src="${pageContext.request.contextPath }/images/head.jpg"
						alt=" " width="100" height="118" align="middle" />
				</c:if>
				<c:if test="${LoginUserImg!=0 }">
					<img
						src="userImg.jsp?id=${id}"
						alt="${id}"
						width="100" height="118" align="middle">
				</c:if>

userImg.jsp:
<%@page contentType="image/jpeg; charset=utf8"%>
<%@page import="java.io.OutputStream"%>
<%
	String id = request.getParameter("id"); 
	Boolean ret = true;
	id = id == null ? "" : id.trim();
	userId = userId == null ? "" : userId.trim();
	OutputStream os = response.getOutputStream();
	if (!id.isEmpty()) {

		ret =UserService.getUserImgById(
				id, os); 
	}  
	os.flush();
	os.close();
	os = null;
	response.flushBuffer();//下面这三句是一定要加上的,否则就会报错。
	out.clear();
	out = pageContext.pushBody();
%>

=================================================================================
后来发现上面的办法并不是最好的解决办法,比如对象User和ClientUser都有byte[] img的属相,那么再Action类中就要分别根据主键id获取对象信息的img属性,然后放到容器中判断byte[]的长度是否为0.那么这是很繁琐的。因此,我想到了一个更好的方法,那就是把读取默认图片也封装成一个方法。java类代码如下:
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

public class DefaultImage {
	public static int getUserImg(OutputStream out, String path) {
		int size = -1;
		FileInputStream is = null;
		try {
			is = new FileInputStream(path);
			// size = is.available(); // 得到文件大小
			byte[] bytes = new byte[1024];
			int len = 0;
			// 开始读取图片信息
			while (-1 != (len = is.read(bytes))) {
				out.write(bytes, 0, len);
				size += len;
			}
			out.flush();
			out.close();
			is.close();
			is = null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return size;

	}
} 

在jsp页面中,这个和上面的一样,没有变化,只是传递一个id到userImg.jsp中。
<c:if test="${LoginUserImg==0 }">
					<img src="${pageContext.request.contextPath }/images/head.jpg"
						alt=" " width="100" height="118" align="middle" />
				</c:if>
				<c:if test="${LoginUserImg!=0 }">
					<img
						src="userImg.jsp?id=${id}"
						alt="${id}"
						width="100" height="118" align="middle">
				</c:if>

userImg.jsp:
<%@page contentType="image/jpeg; charset=utf8"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="com.tools.DefaultImage"%>
<%
	String id = request.getParameter("id");
	String userId = request.getParameter("uid");
	int imgLen = 0;
	id = id == null ? "" : id.trim();/**注意这个地方必须判断一下**/
	userId = userId == null ? "" : userId.trim();
	OutputStream os = response.getOutputStream();

	if (!id.isEmpty()) {
		imgLen = UserService.getUserImgById(
				id, os);//Get Validate Information
	} else if (!userId.isEmpty()) {
		imgLen =UserService
				.getUserImgByUserId(userId, os); 
	}
        //开始读取默认图片
	[color=red]String path = request.getRealPath("/images/head.jpg");[/color]
        //获取项目下的相对路径
	if (imgLen <= 0) {
		imgLen = DefaultImage.getUserImg(os, path);
	} else {
		os.flush();
		os.close();
	}
	os = null;
	response.flushBuffer();
	out.clear();
	out = pageContext.pushBody();
%> 
  
[/size]
1 楼 yuruei2000 2012-04-16  
不错,挺棒!