zoukankan      html  css  js  c++  java
  • hibernate文件上传详解,可以直接使用

    需要先在Tomcat服务器下建立一个upload文件
    package
    cn.jbit.auction.web; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.hibernate.Hibernate; import cn.jbit.auction.biz.IAuctionBiz; import cn.jbit.auction.biz.impl.AuctionBizImpl; import cn.jbit.auction.entity.Auction; import cn.jbit.auction.util.Tool; public class AddAuctionServlet extends EncodingServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String uploadFileName = ""; // 上传的文件名 String fieldName = ""; // 表单字段元素的name属性值(name的值) System.out.println("fieldName="+fieldName); // 判断从表单中请求信息中的内容是否是multipart类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //System.out.println("isMultipart="+isMultipart); // 上传文件的存储路径(服务器文件系统上的绝对文件路径)在tomcat下面 String uploadFilePath = request.getSession().getServletContext() .getRealPath("upload/"); //System.out.println("uploadFilePath="+uploadFilePath); //uploadFilePath=C:Program FilesApache Software FoundationTomcat 7.0webappsauctionupload File fullFile = null; String fileType=null; Auction auction = new Auction(); if (isMultipart) { //为该请求创建一个DiskFileItemFactory对象,通过它来解析请求 FileItemFactory factory = new DiskFileItemFactory(); //System.out.println("factory="+factory); //factory=org.apache.commons.fileupload.disk.DiskFileItemFactory@1cd6b3c ServletFileUpload upload = new ServletFileUpload(factory); // System.out.println("upload="+upload); //upload=org.apache.commons.fileupload.servlet.ServletFileUpload@13b4ed0 // 解析form表单中所有文件 List<FileItem> items = upload.parseRequest(request); // System.out.println("items="+items); //items=[ //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000014.tmp, //size=6bytes, isFormField=true, FieldName=auctionName, //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000015.tmp, //size=5bytes, isFormField=true, FieldName=startPrice, //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000016.tmp, //size=5bytes, isFormField=true, FieldName=upset, //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000017.tmp, //size=19bytes, isFormField=true, FieldName=startTime, //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000018.tmp, //size=19bytes, isFormField=true, FieldName=endTime, //name=C:Program FilesApache Software FoundationTomcat 7.0webappsauctionupload290578.jpg, //StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000019.tmp, //size=208079bytes, isFormField=false, FieldName=pic, //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000020.tmp, //size=7bytes, isFormField=true, FieldName=desc] Iterator<FileItem> iter = items.iterator(); System.out.println("iter="+iter); //iter=java.util.AbstractList$Itr@b34fdc while (iter.hasNext()) { // 依次处理每个文件 FileItem item = (FileItem) iter.next(); //System.out.println("item="+item); //item= //name=null, StoreLocation=C:Program FilesApache Software FoundationTomcat 7.0 empupload_191a43d9_1550ef75687__8000_00000014.tmp, //size=6bytes, isFormField=true, FieldName=auctionName if (item.isFormField()) { // 普通表单字段 fieldName = item.getFieldName(); // 表单字段的name属性值 //System.out.println("item="+item); String value=item.getString("UTF-8"); //System.out.println("value="+value); // 获取表单字段的值 if (fieldName.equals("auctionName")) { auction.setAuctionname(value); } if (fieldName.equals("startPrice")) { auction.setAuctionstartprice(new Double(value)); } if (fieldName.equals("upset")) { auction.setAuctionupset(new Double(value)); } if (fieldName.equals("startTime")) { auction.setAuctionstarttime(new java.sql.Timestamp(Tool.strToDate( value, "yyyy-MM-dd HH:mm:ss").getTime()));//把long转换为Timestamp类型 //Tool.strToDate(value, "yyyy-MM-dd HH:mm:ss").getTime())先把str类型转换为date类型,然后再把date类型转换为1970年至今的毫秒数 //System.out.println("Too="+Tool.strToDate(value, "yyyy-MM-dd HH:mm:ss").getTime()); //Too=1291177800000毫秒数 } if (fieldName.equals("endTime")) { auction.setAuctionendtime(new java.sql.Timestamp(Tool.strToDate( value, "yyyy-MM-dd HH:mm:ss").getTime())); } if (fieldName.equals("desc")) { auction.setAuctiondesc(value); } } else { // 文件表单字段 String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { fullFile = new File(item.getName()); System.out.println("fullFile="+fullFile); System.out.println("fullFile.getName()="+fullFile.getName()); File saveFile = new File(uploadFilePath, fullFile.getName()); item.write(saveFile); uploadFileName = fullFile.getName(); fileType=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1); System.out.println("上传成功后的文件名是:" + uploadFileName); } } } } InputStream is = new FileInputStream(fullFile); byte[] byteArray = new byte[is.available()]; is.read(byteArray); is.close(); IAuctionBiz biz = new AuctionBizImpl(); //设置图片数据 auction.setAuctionpic(Hibernate.createBlob(byteArray)); //设置图片类型 auction.setAuctionpictype(fileType); biz.add(auction); response.sendRedirect("auctionList"); } catch (Exception e) { e.printStackTrace(); request.setAttribute("message", e.getMessage()); request.getRequestDispatcher("error.jsp").forward(request,response); } } /** * Initialization of the servlet. <br> * * @throws ServletException * if an error occurs */ public void init() throws ServletException { // Put your code here } }

    Auction实体类的代码

    package cn.jbit.auction.entity;
    
    import java.sql.Blob;
    import java.sql.Timestamp;
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * Auction entity. @author MyEclipse Persistence Tools
     */
    
    public class Auction implements java.io.Serializable {
    
        // Fields
    
        private Integer auctionid;
        private String auctionname;
        private Double auctionstartprice;
        private Double auctionupset;
        private Timestamp auctionstarttime;
        private Timestamp auctionendtime;
        private Blob auctionpic;
        private String auctionpictype;
        private String auctiondesc;
        private Set auctionrecords = new HashSet(0);
        private String picName;
    
        // Constructors
    
        public String getPicName() {
            return picName;
        }
    
        public void setPicName(String picName) {
            this.picName = picName;
        }
    
        /** default constructor */
        public Auction() {
        }
    
        /** minimal constructor */
        public Auction(String auctionname, Double auctionstartprice,
                Double auctionupset, Timestamp auctionstarttime,
                Timestamp auctionendtime, Blob auctionpic, String auctionpictype) {
            this.auctionname = auctionname;
            this.auctionstartprice = auctionstartprice;
            this.auctionupset = auctionupset;
            this.auctionstarttime = auctionstarttime;
            this.auctionendtime = auctionendtime;
            this.auctionpic = auctionpic;
            this.auctionpictype = auctionpictype;
        }
    
        /** full constructor */
        public Auction(String auctionname, Double auctionstartprice,
                Double auctionupset, Timestamp auctionstarttime,
                Timestamp auctionendtime, Blob auctionpic, String auctionpictype,
                String auctiondesc, Set auctionrecords) {
            this.auctionname = auctionname;
            this.auctionstartprice = auctionstartprice;
            this.auctionupset = auctionupset;
            this.auctionstarttime = auctionstarttime;
            this.auctionendtime = auctionendtime;
            this.auctionpic = auctionpic;
            this.auctionpictype = auctionpictype;
            this.auctiondesc = auctiondesc;
            this.auctionrecords = auctionrecords;
        }
    
        // Property accessors
    
        public Integer getAuctionid() {
            return this.auctionid;
        }
    
        public void setAuctionid(Integer auctionid) {
            this.auctionid = auctionid;
        }
    
        public String getAuctionname() {
            return this.auctionname;
        }
    
        public void setAuctionname(String auctionname) {
            this.auctionname = auctionname;
        }
    
        public Double getAuctionstartprice() {
            return this.auctionstartprice;
        }
    
        public void setAuctionstartprice(Double auctionstartprice) {
            this.auctionstartprice = auctionstartprice;
        }
    
        public Double getAuctionupset() {
            return this.auctionupset;
        }
    
        public void setAuctionupset(Double auctionupset) {
            this.auctionupset = auctionupset;
        }
    
        public Timestamp getAuctionstarttime() {
            return this.auctionstarttime;
        }
    
        public void setAuctionstarttime(Timestamp auctionstarttime) {
            this.auctionstarttime = auctionstarttime;
        }
    
        public Timestamp getAuctionendtime() {
            return this.auctionendtime;
        }
    
        public void setAuctionendtime(Timestamp auctionendtime) {
            this.auctionendtime = auctionendtime;
        }
    
        public Blob getAuctionpic() {
            return this.auctionpic;
        }
    
        public void setAuctionpic(Blob auctionpic) {
            this.auctionpic = auctionpic;
        }
    
        public String getAuctionpictype() {
            return this.auctionpictype;
        }
    
        public void setAuctionpictype(String auctionpictype) {
            this.auctionpictype = auctionpictype;
        }
    
        public String getAuctiondesc() {
            return this.auctiondesc;
        }
    
        public void setAuctiondesc(String auctiondesc) {
            this.auctiondesc = auctiondesc;
        }
    
        public Set getAuctionrecords() {
            return this.auctionrecords;
        }
    
        public void setAuctionrecords(Set auctionrecords) {
            this.auctionrecords = auctionrecords;
        }
    
    }

    Auction实体类的映射文件

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- 
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="cn.jbit.auction.entity.Auction" table="AUCTION">
            <id name="auctionid" type="java.lang.Integer">
                <column name="AUCTIONID" precision="6" scale="0" />
                <generator class="increment" />
            </id>
            <property name="auctionname" type="java.lang.String">
                <column name="AUCTIONNAME" not-null="true" />
            </property>
            <property name="auctionstartprice" type="java.lang.Double">
                <column name="AUCTIONSTARTPRICE" precision="9" not-null="true" />
            </property>
            <property name="auctionupset" type="java.lang.Double">
                <column name="AUCTIONUPSET" precision="9" not-null="true" />
            </property>
            <property name="auctionstarttime" type="java.sql.Timestamp">
                <column name="AUCTIONSTARTTIME" length="11" not-null="true" />
            </property>
            <property name="auctionendtime" type="java.sql.Timestamp">
                <column name="AUCTIONENDTIME" length="11" not-null="true" />
            </property>
            <property name="auctionpic" type="java.sql.Blob">
                <column name="AUCTIONPIC" not-null="true" />
            </property>
            <property name="auctionpictype" type="java.lang.String">
                <column name="AUCTIONPICTYPE" not-null="true" />
            </property>
            <property name="auctiondesc" type="java.lang.String">
                <column name="AUCTIONDESC" />
            </property>
            <set name="auctionrecords" inverse="true" order-by="auctionprice desc">
                <key>
                    <column name="AUCTIONID" precision="6" scale="0" not-null="true" />
                </key>
                <one-to-many class="cn.jbit.auction.entity.Auctionrecord" />
            </set>
        </class>
    </hibernate-mapping>

     jsp文件

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <link href="css/common.css" rel="stylesheet" type="text/css" />
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        function $(id){
            return document.getElementById(id);
        }
        function checkAuctionName(){
            if($("auctionName").value==""){
                $("nameid").style.display="block";
                return false;
            }else{
                $("nameid").style.display="none";
                return true;
            }
        }
        
        function checkStartPrice(){
            if(($("startPrice").value=="")||(isNaN($("startPrice").value)==true)){
                $("startPriceid").style.display="block";
                return false;
            }else{
                $("startPriceid").style.display="none";
                return true;
            }
        }
        
        function checkUpset(){
            if(($("upset").value=="")||(isNaN($("upset").value)==true)){
                $("upsetid").style.display="block";
                return false;
            }else{
                $("upsetid").style.display="none";
                return true;
            }        
        }
        
        function checkStartTime(){
            if($("startTime").value==""){
                $("startTimeid").style.display="block";
                return false;
            }else{
                $("startTimeid").style.display="none";
                return true;
            }        
        }
        
        function checkEndTime(){
            if($("endTime").value==""){
                $("endTimeid").style.display="block";
                return false;
            }else{
                $("endTimeid").style.display="none";
                return true;
            }        
        }
        function checkValue(){
            if((checkAuctionName()&&checkStartPrice()&&checkUpset()&&checkStartTime()&&checkEndTime())==true){                
                if($("pic").value==""){
                    $("picid").style.display="block";
                    return false;
                }else{
                    $("picid").style.display="none";
                    return true;
                }
            }
            return false;
        }
        function showPic(){
            $("imgid").src=$("pic").value;/*考虑到安全性和兼容性问题,发布拍卖品时,图片可以不显示*/
        }
    </script>
    </head>
    
    <body>
            <form action="addAuction" enctype="multipart/form-data" method="post" onsubmit="return checkValue()">
    <div class="wrap">
      <!-- main begin-->
      <div class="sale">
        <h1 class="lf">在线拍卖系统</h1>
        <c:if test="${not empty sessionScope.user}">
            <div class="logout right"><a href="doLogout" title="注销">注销</a></div>
        </c:if>
        <c:if test="${empty sessionScope.user}">
            <div class="logout right"><a href="login.jsp" title="登录">登录</a></div>
        </c:if>
      </div>
          <div class="login logns produce">
            <h1 class="blues">拍卖品信息</h1>
              <dl>
                <dd >
                  <label>名称:</label>
                  <input type="text" onblur="checkAuctionName()" name="auctionName" class="inputh lf" value="" />
                  <div id="nameid" class="lf red laba">名称不能为空</div>
                </dd>
                <dd>
                  <label>起拍价:</label>
                  <input type="text" onblur="checkStartPrice()" name="startPrice" class="inputh lf" value="" />
                  <div id="startPriceid" class="lf red laba">必须为数字</div>
                </dd>
                <dd>
                  <label>底价:</label>
                  <input type="text" name="upset" class="inputh lf" onblur="checkUpset()" value="" />
                  <div id="upsetid" class="lf red laba">必须为数字</div>
                </dd>
                <dd>
                  <label>开始时间:</label>
                  <input type="text" name="startTime" class="inputh lf" value="" onblur="checkStartTime()"/>
                  <div id="startTimeid" class="lf red laba">格式:2010-05-05 12:30:00</div>
                </dd>
                <dd>
                  <label>结束时间:</label>
                  <input type="text" name="endTime" class="inputh lf" value="" onblur="checkEndTime()"/>
                  <div id="endTimeid" class="lf red laba">格式:2010-05-06 16:30:00</div>
                </dd>
                <dd class="dds">
                  <label>拍卖品图片:</label>
                   <div class="lf salebd"><img id="imgid" src="images/ad20.jpg" width="100" height="100" /></div>
                  <input name="pic" type="file" class="offset10 lf"  onchange="showPic()"/>
                 <div id="picid" class="lf red laba">请上传图片</div>
                </dd>
                 <dd class="dds">
                  <label>描述:</label>
                  <textarea name="desc" cols="" rows="" class="textarea"></textarea>
                </dd>
                <dd class="hegas">
                    <input type="submit" value="保 存" class="spbg buttombg buttombgs buttomb f14 lf" />
                    <input type="reset" value="取 消" class="spbg buttombg buttombgs buttomb f14 lf" />
                </dd>
              </dl>
        </div>
    <!-- main end-->
    <!-- footer begin-->
    
    </div>
     <!--footer end-->
     
        </form>
    </body>
    </html>
  • 相关阅读:
    Android 开发笔记___复选框__checkbox
    Android 开发笔记___FrameLayout
    Android 开发笔记___RelativeLayout
    Android 开发笔记___初级控件之实战__计算器
    Android 开发笔记___shape
    Android 开发笔记___DateUtil——Time
    改良版 导航栏自动跟随
    简洁 js排序算法
    简单使用rem方案适配移动设备
    导航栏监听页面滚动跟随 简单封装
  • 原文地址:https://www.cnblogs.com/jimorulang/p/5552682.html
Copyright © 2011-2022 走看看