熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

使用Struts+Hibernate上傳大對象(BLOB)

2022-06-13   來源: Java開源技術 

  流程:首先在addjsp中選擇要上傳的文件或圖片點擊確定Struts中的ActionForm驗證驗證無誤就到Action類中繼續操作Action類調用PhotoDao類的addPhoto方法保存圖片

  :建表

    

  Sql代碼
    create table(
      id int primary key auto_increment
      name varchar()
      photo blob
    )

    create <A title=table target=_blank>table</A>(
      id int primary key auto_increment
      name varchar()
      photo blob
    )

  create table(
      id int primary key auto_increment
      name varchar()
      photo blob
    )

    addjsp頁面代碼

  Html代碼
      <%@ page language=java pageEncoding=ISO%>
    <%@ taglib uri=bean prefix=bean%>
    <%@ taglib uri=html prefix=html%>

  <html>
        <head>
            <title>JSP for AddForm form</title>
        </head>
        <body>
            <html:form action=/add enctype=multipart/formdata>
                name : <html:text property=name/><html:errors property=name/><br/>
                photo : <html:file property=photo/><html:errors property=photo/><br/>
                <html:submit/><html:cancel/>
            </html:form>
        </body>
    </html>
    view plaincopy to clipboardprint?
    <%@ page language=java pageEncoding=ISO%>
    <%@ taglib uri=bean prefix=bean%>
    <%@ taglib uri=html prefix=html%>

  <html>
        <head>
            <title>JSP for AddForm form</title>
        </head>
        <body>
            <html:form action=/add enctype=multipart/formdata>
                name : <html:text property=name/><html:errors property=name/><br/>
                photo : <html:file property=photo/><html:errors property=photo/><br/>
                <html:submit/><html:cancel/>
            </html:form>
        </body>
    </html>

  <%@ page language=java pageEncoding=ISO%>
    <%@ taglib uri=bean prefix=bean%>
    <%@ taglib uri=html prefix=html%>

  <html>
     <head>
      <title>JSP for AddForm form</title>
     </head>
     <body>
      <html:form action=/add enctype=multipart/formdata>
       name : <html:text property=name/><html:errors property=name/><br/>
       photo : <html:file property=photo/><html:errors property=photo/><br/>
       <html:submit/><html:cancel/>
      </html:form>
     </body>
    </html> :photo(javabean)代碼如下

  Java代碼
    package comhpentity;

  import javasqlBlob;

  public class Photo implements javaioSerializable {

  private Integer id;
        private String name;
        private Blob photo;

  public Photo() {
        }

  public Photo(String name) {
            thisname = name;
        }

  public Photo(String name Blob photo) {
            thisname = name;
            thisphoto = photo;
        }

  public Integer getId() {
            return thisid;
        }

  public void setId(Integer id) {
            thisid = id;
        }

  public String getName() {
            return thisname;
        }

  public void setName(String name) {
            thisname = name;
        }

  public Blob getPhoto() {
            return photo;
        }

  public void setPhoto(Blob photo) {
            thisphoto = photo;
        }

  }
    view plaincopy to clipboardprint?
    package comhpentity;

  import javasqlBlob;

  public class Photo implements javaioSerializable {

  private Integer id;
        private String name;
        private Blob photo;

  public Photo() {
        }

  public Photo(String name) {
            thisname = name;
        }

  public Photo(String name Blob photo) {
            thisname = name;
            thisphoto = photo;
        }

  public Integer getId() {
            return thisid;
        }

  public void setId(Integer id) {
            thisid = id;
        }

 

          public String getName() {
            return thisname;
        }

  public void setName(String name) {
            thisname = name;
        }

  public Blob getPhoto() {
            return photo;
        }

  public void setPhoto(Blob photo) {
            thisphoto = photo;
        }

  }

  package comhpentity;

  import javasqlBlob;

  public class Photo implements javaioSerializable {

  private Integer id;
     private String name;
     private Blob photo;

  public Photo() {
     }

  public Photo(String name) {
      thisname = name;
     }

  public Photo(String name Blob photo) {
      thisname = name;
      thisphoto = photo;
     }

  public Integer getId() {
      return thisid;
     }

  public void setId(Integer id) {
      thisid = id;
     }

  public String getName() {
      return thisname;
     }

  public void setName(String name) {
      thisname = name;
     }

  public Blob getPhoto() {
      return photo;
     }

  public void setPhoto(Blob photo) {
      thisphoto = photo;
     }

  }

  Xml代碼
    <?xml version= encoding=utf?>

  <!DOCTYPE hibernatemapping PUBLIC //Hibernate/Hibernate Mapping DTD //EN

  mappingdtd>

  <!

  Mapping file autogenerated by MyEclipse Persistence Tools

  >

  <Hibernatemapping>

  <class name=comhpentityPhoto table=photo catalog=test>

  <id name=id type=javalangInteger>

  <column name=id />

  <generator class=native />

  </id>

  <property name=name type=javalangString>

  <column name=name length= notnull=true />

  </property>

  <!注意下面的類型>

  <property name=photo type=javasqlBlob>

  <column name=photo />

  </property>

  </class>

  </Hibernatemapping>
    view plaincopy to clipboardprint?
    <?xml version= encoding=utf?>

  <!DOCTYPE <A title=Hibernate 基金&amp;amp;q=基金&amp;amp;sbb=搜索&amp;amp;sa=搜索&amp;amp;client=pub&amp;amp;forid=&amp;amp;prog=aff&amp;amp;ie=GB&amp;amp;oe=GB&amp;amp;hl=zhCN target=_blank>Hibernate</A>mapping PUBLIC //Hibernate/Hibernate Mapping DTD //EN

  mappingdtd>

  <!

  Mapping file autogenerated by MyEclipse Persistence Tools

  >

  <hibernatemapping>

  <class name=comhpentityPhoto <A title=table target=_blank>table</A>=photo catalog=test>

  <id name=id type=javalangInteger>

  <column name=id />

  <generator class=native />

  </id>

  <property name=name type=javalangString>

  <column name=name length= notnull=true />

  </property>

  <!注意下面的類型>

  <property name=photo type=javasqlBlob>

  <column name=photo />

  </property>

  </class>

  </hibernatemapping>

  <?xml version= encoding=utf?>

  <!DOCTYPE Hibernatemapping PUBLIC //Hibernate/Hibernate Mapping DTD //EN

  mappingdtd>

  <!

  Mapping file autogenerated by MyEclipse Persistence Tools

  >

  <hibernatemapping>

  <class name=comhpentityPhoto table=photo catalog=test>

  <id name=id type=javalangInteger>

  <column name=id />

  <generator class=native />

  </id>

  <property name=name type=javalangString>

  <column name=name length= notnull=true />

  </property>

  <!注意下面的類型>

  <property name=photo type=javasqlBlob>

  <column name=photo />

  </property>

  </class>

  </hibernatemapping>    :PhotoDao代碼如下

  Java代碼
    import orghibernateQuery;

  import orghibernateSession;

  import orghibernateTransaction;

  import comhpentityPhoto;

  import comhputil*;

  public class PhotoDao {

  private Session session=null;

  public PhotoDao(){

  thissession = HibernateSessionFactorygetSession();

  }

  public void addPhoto(Photo photo){

  Transaction tx=sessionbeginTransaction();

  sessionsaveOrUpdate(photo);

  mit();

  }

  public Photo getByName(String name){

  Query query=sessioncreateQuery(from Photo p where pname = ?);

  querysetString(name);

  return (Photo) queryuniqueResult();

  }

  public void close(){

  if(sessionisOpen()){

  sessionclose();

  session=null;

  }

  }

  }

    import orghibernateQuery;

  import orghibernateSession;

  import orghibernateTransaction;

  import comhpentityPhoto;

  import comhputil*;

  public class PhotoDao {

  private Session session=null;

  public PhotoDao(){

              thissession = HibernateSessionFactorygetSession();

  }

  public void addPhoto(Photo photo){

  Transaction tx=sessionbeginTransaction();

  sessionsaveOrUpdate(photo);

  mit();

  }

  public Photo getByName(String name){

  Query query=sessioncreateQuery(from Photo p where pname = ?);

  querysetString(name);

  return (Photo) queryuniqueResult();

  }

  public void close(){

  if(sessionisOpen()){

  sessionclose();

  session=null;

  }

  }

  }

  import orghibernateQuery;

  import orghibernateSession;

  import orghibernateTransaction;

  import comhpentityPhoto;

  import comhputil*;

  public class PhotoDao {

  private Session session=null;

  public PhotoDao(){

  thissession = HibernateSessionFactorygetSession();

  }

  public void addPhoto(Photo photo){

  Transaction tx=sessionbeginTransaction();

  sessionsaveOrUpdate(photo);

  mit();

  }

  public Photo getByName(String name){

  Query query=sessioncreateQuery(from Photo p where pname = ?);

  querysetString(name);

  return (Photo) queryuniqueResult();

  }

  public void close(){

  if(sessionisOpen()){

  sessionclose();

  session=null;

  }

  }

  }

  :struts的ActionForm代碼

  Java代碼
    import javaxservlethttpHttpServletRequest;

  import orgapachestrutsactionActionErrors;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  public class AddForm extends ActionForm {

  //在Struts中上傳文件需要使用FormFile類型

  private FormFile photo;
        private String name;

  public ActionErrors validate(ActionMapping mapping

  HttpServletRequest request) {

  return null;

  }
        public void reset(ActionMapping mapping HttpServletRequest request) {

  }

  public FormFile getPhoto() {

  return photo;

  }
        public void setPhoto(FormFile photo) {

  thisphoto = photo;

  }
        public String getName() {

  return name;

  }
        public void setName(String name) {

  thisname = name;

  }

  }

    import javaxservlethttpHttpServletRequest;

  import orgapachestrutsactionActionErrors;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  public class AddForm extends ActionForm {

  //在Struts中上傳文件需要使用FormFile類型

  private FormFile photo;
        private String name;

  public ActionErrors validate(ActionMapping mapping

  HttpServletRequest request) {

  return null;

  }
        public void reset(ActionMapping mapping HttpServletRequest request) {

  }

  public FormFile getPhoto() {

  return photo;

  }
        public void setPhoto(FormFile photo) {

  thisphoto = photo;

  }
        public String getName() {

  return name;

  }
        public void setName(String name) {

  thisname = name;

  }

  }

  import javaxservlethttpHttpServletRequest;

  import orgapachestrutsactionActionErrors;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  public class AddForm extends ActionForm {

  //在Struts中上傳文件需要使用FormFile類型

  private FormFile photo;
        private String name;

  public ActionErrors validate(ActionMapping mapping

  HttpServletRequest request) {

  return null;

  }
        public void reset(ActionMapping mapping HttpServletRequest request) {

  }

  public FormFile getPhoto() {

  return photo;

  }
        public void setPhoto(FormFile photo) {

  thisphoto = photo;

  }
        public String getName() {

  return name;

  }
        public void setName(String name) {

  thisname = name;

  }

  }

  :struts的Action代碼

  Java代碼
    import javaioFile;

  import javaioFileInputStream;

  import javaioFileNotFoundException;

  import javaioFileOutputStream;

  import javaioIOException;

  import javaioInputStream;

  import javaioOutputStream;

    

  import javasqlBlob;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  import orghibernateHibernate;

  import comdao*;

  import comhpentityPhoto;

  import comhpstrutsformAddForm;

  public class AddAction extends Action {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response) {

  AddForm addForm = (AddForm) form;

  String name = addFormgetName();

  // 在Struts中上傳文件需要使用FormFile

  FormFile formFile = addFormgetPhoto();

  Systemoutprintln(name = + name);

  Systemoutprintln(size = + formFilegetFileSize());

  Photo photo= new Photo();

  //將FormFile類型的圖片信息轉換為字節數組類型

  try {

  byte[] buf= formFilegetFileData();

  //使用Hibernate的工具將字節數組轉換成Blob對象

  Blob ph= HibernatecreateBlob(buf);

  photosetName(name);

  photosetPhoto(ph);

  PhotoDao photoDao = new PhotoDao();

  photoDaoaddPhoto(photo);

  //以上為插入圖片下面為讀取剛才插入的圖片按name查找圖片

  Photo temp = photoDaogetByName(name);

  //將BLOB對象轉化為輸入流的形式

  InputStream in=tempgetPhoto()getBinaryStream();

  //先在C盤生成temp文件用於保存圖片

  OutputStream os = new FileOutputStream(new File(c://tempjpg));

  //把輸入流中的數據讀入buf數組中

  inread(buf);

  //從buf數組中讀出數據

  oswrite(buf);

  inclose();

  osclose();

  requestgetSession()setAttribute(photoc://tempjpg);

  photoDaoclose();

  } catch (Exception e) {

  eprintStackTrace();

  }

  return mappingfindForward(success);

  }

  public static void main(String[] args) {

  Systemoutprintln(SystemgetProperty(userdir));

  }

  }

    import javaioFile;

  import javaioFileInputStream;

  import javaioFileNotFoundException;

  import javaioFileOutputStream;

  import javaioIOException;

  import javaioInputStream;

  import javaioOutputStream;

  import javasqlBlob;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  import orghibernateHibernate;

  import comdao*;

  import comhpentityPhoto;

  import comhpstrutsformAddForm;

  public class AddAction extends Action {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response) {

  AddForm addForm = (AddForm) form;

  String name = addFormgetName();

  // 在Struts中上傳文件需要使用FormFile

  FormFile formFile = addFormgetPhoto();

  <A title=system target=_blank>system</A>outprintln(name = + name);

  <A title=system target=_blank>system</A>outprintln(size = + formFilegetFileSize());

  Photo photo= new Photo();

  //將FormFile類型的圖片信息轉換為字節數組類型

  try {

  byte[] buf= formFilegetFileData();

  //使用Hibernate的工具將字節數組轉換成Blob對象

  Blob ph= <A title=Hibernate 基金&amp;amp;q=基金&amp;amp;sbb=搜索&amp;amp;sa=搜索&amp;amp;client=pub&amp;amp;forid=&amp;amp;prog=aff&amp;amp;ie=GB&amp;amp;oe=GB&amp;amp;hl=zhCN target=_blank>Hibernate</A>createBlob(buf);

  photosetName(name);

  photosetPhoto(ph);

  PhotoDao photoDao = new PhotoDao();

  photoDaoaddPhoto(photo);

  //以上為插入圖片下面為讀取剛才插入的圖片按name查找圖片

  Photo temp = photoDaogetByName(name);

  //將BLOB對象轉化為輸入流的形式

  InputStream in=tempgetPhoto()getBinaryStream();

  //先在C盤生成temp文件用於保存圖片

  OutputStream os = new FileOutputStream(new File(c://tempjpg));

  //把輸入流中的數據讀入buf數組中

  inread(buf);

  //從buf數組中讀出數據

  oswrite(buf);

  inclose();

  osclose();

  requestgetSession()setAttribute(photoc://tempjpg);

  photoDaoclose();

  } catch (Exception e) {

  eprintStackTrace();

  }

  return mappingfindForward(success);

  }

  public static void main(String[] args) {

  <A title=system target=_blank>system</A>outprintln(SystemgetProperty(userdir));

  }

  }

  import javaioFile;

  import javaioFileInputStream;

  import javaioFileNotFoundException;

  import javaioFileOutputStream;

  import javaioIOException;

  import javaioInputStream;

  import javaioOutputStream;

  import javasqlBlob;

  import javaxservlethttpHttpServletRequest;

      import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  import orghibernateHibernate;

  import comdao*;

  import comhpentityPhoto;

  import comhpstrutsformAddForm;

  public class AddAction extends Action {

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response) {

  AddForm addForm = (AddForm) form;

  String name = addFormgetName();

  // 在Struts中上傳文件需要使用FormFile

  FormFile formFile = addFormgetPhoto();

  systemoutprintln(name = + name);

  systemoutprintln(size = + formFilegetFileSize());

  Photo photo= new Photo();

  //將FormFile類型的圖片信息轉換為字節數組類型

  try {

  byte[] buf= formFilegetFileData();

  //使用Hibernate的工具將字節數組轉換成Blob對象

  Blob ph= HibernatecreateBlob(buf);

  photosetName(name);

  photosetPhoto(ph);

  PhotoDao photoDao = new PhotoDao();

  photoDaoaddPhoto(photo);

  //以上為插入圖片下面為讀取剛才插入的圖片按name查找圖片

  Photo temp = photoDaogetByName(name);

  //將BLOB對象轉化為輸入流的形式

  InputStream in=tempgetPhoto()getBinaryStream();

  //先在C盤生成temp文件用於保存圖片

  OutputStream os = new FileOutputStream(new File(c://tempjpg));

  //把輸入流中的數據讀入buf數組中

  inread(buf);

  //從buf數組中讀出數據

  oswrite(buf);

  inclose();

  osclose();

  requestgetSession()setAttribute(photoc://tempjpg);

  photoDaoclose();

  } catch (Exception e) {

  eprintStackTrace();

  }

  return mappingfindForward(success);

  }

  public static void main(String[] args) {

  systemoutprintln(SystemgetProperty(userdir));

  }

  }

  :用於顯示插入圖片的頁面showjsp

  Html代碼
    <%@ page language=java pageEncoding=ISO%>

  <%@ taglib uri=bean prefix=bean %>

  <%@ taglib uri=html prefix=html %>

  <%@ taglib uri=logic prefix=logic %>

  <%@ taglib uri=tiles prefix=tiles %>

  <!DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN>

  <html:html lang=true>

  <head>

  <html:base />

  <title>showjsp</title>

  </head>

  <body>

  <html:img src=${photo}/>

  </body>

  </html:html>
    view plaincopy to clipboardprint?
    <%@ page language=java pageEncoding=ISO%>

  <%@ taglib uri=bean prefix=bean %>

  <%@ taglib uri=html prefix=html %>

  <%@ taglib uri=logic prefix=logic %>

  <%@ taglib uri=tiles prefix=tiles %>

  <!DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN>

  <html:html lang=true>

  <head>

  <html:base />

  <title>showjsp</title>

  </head>

  <body>

  <html:img src=${photo}/>

  </body>

  </html:html>


From:http://tw.wingwit.com/Article/program/Java/ky/201311/27966.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.