iT邦幫忙

0

【左京淳的JAVA WEB學習筆記】第十五章 商品上架&用戶購買紀錄

管理員在網站後台,需有商品上、下架操作功能。

新建BookAdd.jsp

  <form action="<%=basePath%>back/BookAddSvl" method="post" enctype="multipart/form-data" id="myform">
    <table border="0" width="60" align="center">
      <tr>
        <td>書號ISBN</td>
        <td>
          <input type="text" name="isbn" value="${isbn }" id="isbn" onkeyup="isValid()">
          <span id="isbnAlert" style="color:red;font-size:8px;"></span>
        </td>
      </tr>
      <tr>
        <td>書名</td>
        <td><input type="text" name="bname" value="${bname }" id="bname"></td>
      </tr>
      <tr>
        <td>出版社</td>
        <td><input type="text" name="press" value="${press }"></td>
      </tr>
      <tr>
        <td>出版日期</td>
        <td><input type="text" name="pdate" value="${pdate }" class="easyui-datebox"></td>
      </tr>
      <tr>
        <td>價格</td>
        <td><input type="text" name="price" value="${price }" class="easyui-numberbox" value="0" precision="2"></td>
      </tr>
      <tr>
        <td>圖片上傳</td>
        <td><input type="file" name="pic"></td>
      </tr>
      <tr>
        <td></td>
        <td>
          <input type="button" value="送出" onclick="submit()">
          <p style="color:red;font-size:8px;">${msg }</p>
          <span id="info" style="color:red;font-size:8px;"></span>
        </td>
      </tr>
    </table>
  </form>

記憶重點

  • 表單中有檔案上傳時,enctype="multipart/form-data"
  • 使用onkeyup="isValid()進行書號確認
  • 使用onclick="submit()"進行商品上架
    (方法的細節請參閱前面章節)

新建BoodAddSvl

@WebServlet("/back/BookAddSvl")
@MultipartConfig(maxFileSize=100*1024)
public class BookAddSvl extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/back/BookAdd.jsp");
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String isbn = request.getParameter("isbn");
    String bname = request.getParameter("bname");
    String press = request.getParameter("press");
    String pdate = request.getParameter("pdate");
    String price = request.getParameter("price");
    TBook book = new TBook();
    book.setIsbn(isbn);
    book.setBname(bname);
    book.setPress(press);
    //pdate與price需要套用格式所以處理稍微不同
    if(pdate != null && !pdate.equals("")) {
      SimpleDateFormat sd = new SimpleDateFormat();
      try {
        book.setPdate(sd.parse(pdate));
      }catch(Exception e) {
        Log.logger.error(e.getMessage(),e);
      }
    }
    if(price != null && !price.equals("")) {
      try {
        book.setPrice(Double.parseDouble(price));
      }catch(Exception e) {
        Log.logger.error(e.getMessage(),e);
      }
    }
    try {
      Part part = request.getPart("pic");
      InputStream in = part.getInputStream();
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buff = new byte[1024];
      int len;
      //若in.read(buff)能讀到資料,把資料長度設給len,讓out寫出資料(從0寫到len的長度)
      while((len = in.read(buff)) != -1) {
        out.write(buff, 0, len);
      }
      //out寫出完成後,把資料轉存為byte[]
      byte[] pic = out.toByteArray();
      
      //存入javaBean
      book.setPic(pic);
      
      //將javaBean加入DB中
      BookBiz biz = new BookBiz();
      biz.addBook(book);
      request.setAttribute("msg", bname + "上傳成功");
      request.getRequestDispatcher("/WEB-INF/back/Bookadd.jsp").forward(request, response);
    }catch(Exception e){
      Log.logger.error(e.getMessage(),e);
      request.setAttribute("msg", e.getMessage());
      request.getRequestDispatcher("/error.jsp").forward(request, response);
    }
  }
}

記憶重點

  1. 將表格資料存到javaBean中,需轉換的資料要先進行非空判定。
  2. 圖片檔上傳
  3. 將陣列檔案存進javaBean
  4. 將javaBean存進DB
  5. 將成功或失敗訊息設給request並轉發至其他網頁。

檔案上傳步驟:

  1. 使用request.getPart("pic")取得檔案
  2. 使用part.getInputStream()取得輸入流
  3. 使用new ByteArrayOutputStream()取得輸出流
  4. 使用in.read(buff)讀取檔案,搭配while迴圈使用out.write(buff, 0, len)將檔案寫出到輸出流
  5. 使用out.toByteArray()將輸出流轉成2位元陣列

在BookBiz新增addBook()

  public void addBook(TBook book) {
    IBookDao dao = new BookDaoMysql();
    try {
      dao.addBook(book);
    }finally {
      dao.closeConnection();
    }
  }

在BookDaoMysql新增addBook()

  public void addBook(TBook book) throws Exception{
    String sql = "insert into tbook(isbn,bname,press,price,pdate,pic,bkcount) value(?,?,?,?,?,?,?)";
    this.openConnection(); 
    PreparedStatement ps = this.connection.prepareStatement(sql);
    ps.setString(1, book.getIsbn());
    ps.setString(2, book.getBname());
    ps.setString(3, book.getPress());
    ps.setDouble(4, book.getPrice());
    ps.setDate(5, new java.sql.Date(book.getPdate().getTime()));
    ps.setBytes(6, book.getPic());
    ps.setInt(7, 1000);
    ps.executeUpdate();
    ps.close();
  }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言