实现功能是 用户本地浏览一个图片后(本来要用上传 为简单起见就制作本地测试) 功过Hibernate中向数据库插入图片 并在另一个页面把这个图片显示出来
index.jsp
一个简单的表单用于浏览图片
Img.java
public class Img implements java.io.Serializable {
// Fields
private Integer id;
privatebyte[] img;
......
}
Img.hbm.xml
servlet中的处理方式 (web.xml 中 /imgServlet 对这个servlet的配置)
public void doPostt(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
//PrintWriter out2 = response.getWriter();
//servlet 中 out 对象只可取一次.
//如果要用与输出二进制数据 . 就必须用 OutputStream 对象.
OutputStream out = response.getOutputStream();
request.setCharacterEncoding("UTF-8");
String path = request.getParameter("path");
java.io.File file = new File(path);
InputStream inputStream = new FileInputStream(file);
byte[] buff= new byte[(int) file.length()];
inputStream.read(buff, 0, (int) file.length());
Img img = new Img();
img.setImg(buff);
Session session = HibernateSessionFactory.getSession();
session.save(img);
session.beginTransaction().commit();
String realPath = request.getSession().getServletContext().getRealPath("/");
System.out.println("realPath"+realPath);
System.out.println("path:"+path);
System.out.println("插入成功!!!");
try {
//将图片写入到输出流中
out.write(img.getImg()); } catch (Exception e) {
e.printStackTrace();
}
//request.getRequestDispatcher("show.jsp").forward(request, response);
response.sendRedirect("show.jsp");
out.flush();
out.close();
}
show.jsp
通过提交就可以在 show.jsp看到用户提交的图片并且改图片保存到了数据库