2016-05-30 34 views
-2
package com.gtlsoftware; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
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 javax.servlet.http.HttpSession; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import java.sql.PreparedStatement; 
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB 
maxFileSize=1024*1024*10,  // 10MB 
maxRequestSize=1024*1024*50) // 50MB 
public class MenuServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    public MenuServlet() 
    { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    { 
     Connection con; 
     ResultSet rs; 
     PreparedStatement pst; 
     //INSERT INTO DATABASE 

      PrintWriter pw=response.getWriter(); 
      pw.print("hello"); 
      String name=request.getParameter("name"); 

      pw.println(name); 

      System.out.println(name); 
      String description = request.getParameter("description"); 
      String image = request.getParameter("image"); 
      String category=request.getParameter("category"); 
      String unit=request.getParameter("unit"); 
      String units=request.getParameter("units"); 
      String price=request.getParameter("price"); 

      byte[] b=null; 

     try 
      { 
      con=MyConnection.getConnection(); 
      DiskFileItemFactory factory = new DiskFileItemFactory(); 

      ServletFileUpload sfu = new ServletFileUpload(factory); 
      List items = sfu.parseRequest(request); 

      Iterator iter = items.iterator(); 

      while (iter.hasNext()) 
      { 
       FileItem item = (FileItem) iter.next(); 
       if (!item.isFormField()) 
       { 
        b = item.get(); 
       } 
      } 
      pst=con.prepareStatement("insert into menu(menu_name,description,image,category,unit,units,price) values(?,?,?,?,?,?,?)"); 
      pst.setString(1, name); 
      pst.setString(2, description); 
      pst.setBytes(3,b); 
      pst.setString(4, category); 
      pst.setString(5, unit); 
      pst.setString(6,units); 
      pst.setString(7,price); 
      pst.executeUpdate(); 
      System.out.println("inserted successfully"); 
     } 
     catch (SQLException e) 
     { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     catch (FileUploadException e) 
     { 
      System.out.println(e.getMessage()); 
      // TODO: handle exception 
     } 


    } 

} 

我沒有編碼圖像插入。但當我在表單的enctype使用=「的multipart/form-data的那麼空值去我也下頁增加公共記錄和文件上傳的罐子,如果我刪除加密類型,然後插入值,但圖像沒有插入正在採取圖像中LONGBLOB我沒有在jsp頁面編碼,但下頁它給空值

和JSP頁面引入了menu.jsp

<body> 
    <center> 
     <div> 
     <table border="0" cellspacing="10" cellpadding="5" style="text-align: left"> 
      <tr> 
       <td><%@ include file="header.jsp" %></td> 
      </tr> 
      <tr> 
       <td> 
        <div class="main_div"> 
        <fieldset> 
          <form name="menuFrm" action="MenuServlet" method="post" onsubmit="reurn(validate())" enctype="multipart/form-data" > 
           <table cellspacing="7" cellpadding="2" align="center" border="0" style="font-family: sans-serif;font-weight: normal;font-size: medium"> 
           <tr> 
            <td colspan="2" style="background-color: black;color: white;font-family: Centaur;font-size: 20px;text-align: center;"> 
             <h4>Menu</h4> 
            </td> 
           </tr> 
           <tr> 
            <td>Menu Id :</td> 
            <td><input type="text" name="menuId" id="MenuId" value="<%=++cnt %>" tabindex="1" size="30%" placeholder="enter menu name"></td> 

           </tr> 
           <tr> 
            <td>Name :</td> 
            <td><input type="text" name="name" id="name" value="hdsuidd" tabindex="1" size="30%" placeholder="enter menu name"></td> 
           </tr> 
           <tr> 
            <td>Description:</td> 
            <td><textarea rows="6" cols="30" name="description" size="30%" tabindex="4" id="description" size="30%" placeholder="enter description"></textarea></td> 
           </tr> 
           <tr> 
             <td>Image:</td> 
            <td><input type="file" class="txtset" id="image" name="image" tabindex="5"/></td> 
            </form> 
           </tr> 
           <tr> 
            <td>Category:</td> 
            <td> 
             <select id="category" class="txtset" name="category"> 
              <option selected="selected">select category</option> 
              <option value="veg">Veg</option> 
              <option value="non-veg">Non-Veg</option> 
             </select> 

            </td> 
           </tr> 
           <tr> 
            <td>Units:</td> 
            <td><input type="text" name="unit" id="unit" class="txtset" tabindex="6" width="10%" onkeyup="myNum()"/> 
             <select id="units" name="units"> 
              <option selected="selected">select units</option> 
              <option value="kg">KG</option> 
              <option value="gram">GRAM</option> 
              <option value="unit">Unit</option> 
             </select> 


            </td> 
           </tr> 
           <tr> 
            <td>Price:</td> 
            <td><input type="text" name="price" class="txtset" id="price" onkeyup="myNum()" tabindex="7" width="30%" height="10%">&nbsp;&nbsp;/-Rs.</td> 
           </tr> 
           <tr> 
             <td><font color='white'> <DIV id="une" style="background-color: red;font-weight: bold;"> </DIV> </font></td> 
           </tr> 
           <tr> 
            <td><input type="submit" value="Add" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="valid();check()"/></td> 
            <td><input type="reset" value="Cancel" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="reset()"/></td> 
           </tr> 
           <tr> 
            <td colspan="2"> 
             <br> 
             <br> 
              <a href="edit.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;"> 
               <u>Edit</u></a> 
              &nbsp; &nbsp; &nbsp; 
              <a href="update.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;"> 
              <u>Update</u></a> 
              &nbsp; &nbsp; &nbsp; 
              <a href="delete.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px";> 
              <u>Delete</u></a> 
              &nbsp; &nbsp; &nbsp; 

            </td> 
           </tr> 
          </table> 


         </form> 
          <% 
           con.close(); 
          %> 

        </fieldset> 
        </div> 

       </td> 
      </tr> 
      <tr> 
       <td><%@ include file="footer.jsp" %></td> 
      </tr> 
     </table> 
     </div> 
    </center> 




</body> 
+0

請給我一些建議,我必須做的 –

回答

-1

您正在使用錯誤的代碼,以接收和在servlet中插入圖像圖像總是作爲多部分數據發送到servlet,因此使用form enctype="multipart/form-data i這是正確的。但是在你的servlet中,你正在接收圖像作爲參數,這是錯誤的。形象應該是收到部分數據是這樣的: -

Part filePart=request.getPart("image"); 

然後我們檢索部分數據這樣的文件路徑: -

String filePath = filePart.getSubmittedFileName(); 

後,我們從路徑檢索圖像文件,然後將其轉換爲文件輸入流,以便它可以被插入作爲二進制數據: -

File image = new File(filePath); 
FileInputStream fis = new FileInputStream(image); 

它正確的語句插入圖像後是這樣的: -

pst.setBinaryStream (3, fis, (int) image.length()); 

這裏3是表中longblob數據的列值。在您的servlet中進行這些修改後,我確信您的所有表單數據都將成功插入到您的數據庫中。是的,從你的代碼刪除這些下面幾行: -

pw.print("hello"); 
pw.println(name); 
System.out.println("inserted successfully"); 

創建名爲SuccessPage.html和FailurePage.html兩個HTML頁打印哪些成功和失敗消息安慰和這樣的插入操作的最後一行代碼: -

int rowCount=pst.executeUpdate(); 
if(rowCount>0){ 
      response.sendRedirect("SuccessPage.jsp"); 
     } 
     else{ 
      response.sendRedirect("FailurePage.jsp"); 
     } 

PS :更換你mulitpart配置行: -

@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB 
maxFileSize=1024*1024*10,  // 10MB 
maxRequestSize=1024*1024*50) // 50MB 

本: -

@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024*2, maxFileSize=1024*1024*10, maxRequestSize=1024*1024*50) 

如果這個答案可以幫助你,通過點擊它的左上角右標記接受它。如果沒有,請告訴我。所有最優秀的:) 下面是修改後的JSP: -

<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
    </head> 
    <body> 
    <center> 
     <div> 
     <table border="0" cellspacing="10" cellpadding="5" style="text-align: left"> 
      <%--<tr> 
       <td><%@ include file="header.jsp" %></td> 
      </tr>--%> 
      <tr> 
       <td> 
        <div class="main_div"> 
        <fieldset> 
          <form name="menuFrm" action="SOQ52" method="post" onsubmit="reurn(validate())" enctype="multipart/form-data" > 
           <table cellspacing="7" cellpadding="2" align="center" border="0" style="font-family: sans-serif;font-weight: normal;font-size: medium"> 
           <tr> 
            <td colspan="2" style="background-color: black;color: white;font-family: Centaur;font-size: 20px;text-align: center;"> 
             <h4>Menu</h4> 
            </td> 
           </tr> 
           <tr> 
            <td>Menu Id :</td> 
            <td><input type="text" name="menuId" id="MenuId" tabindex="1" size="30%" placeholder="enter menu name"></td> 

           </tr> 
           <tr> 
            <td>Name :</td> 
            <td><input type="text" name="name" id="name" tabindex="1" size="30%" placeholder="enter menu name"></td> 
           </tr> 
           <tr> 
            <td>Description:</td> 
            <td><textarea rows="6" cols="30" name="description" size="30%" tabindex="4" id="description" size="30%" placeholder="enter description"></textarea></td> 
           </tr> 
           <tr> 
             <td>Image:</td> 
            <td><input type="file" class="txtset" id="image" name="image" tabindex="5"/></td> 
            </form> 
           </tr> 
           <tr> 
            <td>Category:</td> 
            <td> 
             <select id="category" class="txtset" name="category"> 
              <option selected="selected">select category</option> 
              <option value="veg">Veg</option> 
              <option value="non-veg">Non-Veg</option> 
             </select> 

            </td> 
           </tr> 
           <tr> 
            <td>Units:</td> 
            <td><input type="text" name="unit" id="unit" class="txtset" tabindex="6" width="10%" onkeyup="myNum()"/> 
             <select id="units" name="units"> 
              <option selected="selected">select units</option> 
              <option value="kg">KG</option> 
              <option value="gram">GRAM</option> 
              <option value="unit">Unit</option> 
             </select> 


            </td> 
           </tr> 
           <tr> 
            <td>Price:</td> 
            <td><input type="text" name="price" class="txtset" id="price" onkeyup="myNum()" tabindex="7" width="30%" height="10%">&nbsp;&nbsp;/-Rs.</td> 
           </tr> 
           <tr> 
             <td><font color='white'> <DIV id="une" style="background-color: red;font-weight: bold;"> </DIV> </font></td> 
           </tr> 
           <tr> 
            <td><input type="submit" value="Add" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="valid();check()"/></td> 
            <td><input type="reset" value="Cancel" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="reset()"/></td> 
           </tr> 
           <tr> 
            <td colspan="2"> 
             <br> 
             <br> 
              <a href="edit.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;"> 
               <u>Edit</u></a> 
              &nbsp; &nbsp; &nbsp; 
              <a href="update.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;"> 
              <u>Update</u></a> 
              &nbsp; &nbsp; &nbsp; 
              <a href="delete.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px";> 
              <u>Delete</u></a> 
              &nbsp; &nbsp; &nbsp; 

            </td> 
           </tr> 
          </table> 


         </form> 

        </fieldset> 
        </div> 

       </td> 
      </tr> 
      <%--<tr> 
       <td><%@ include file="footer.jsp" %></td> 
      </tr>--%> 
     </table> 
     </div> 
    </center> 
</body> 
</html> 

,這是你的servlet: -

import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
//import org.apache.commons.fileupload.FileItem; 
//import org.apache.commons.fileupload.FileUploadException; 
//import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
//import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import java.sql.PreparedStatement; 
import javax.servlet.annotation.MultipartConfig; 
import javax.servlet.http.Part; 
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB 
maxFileSize=1024*1024*10,  // 10MB 
maxRequestSize=1024*1024*50) // 50MB 
public class SOQ52 extends HttpServlet { 
    private static final long serialVersionUID = 1L; 


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    { 
     //Connection con; 
     ResultSet rs; 
     PreparedStatement pst; 
     //INSERT INTO DATABASE 

      PrintWriter out=response.getWriter(); 
      //pw.print("hello"); 
      String name=request.getParameter("name"); 

      //pw.println(name); 

      System.out.println(name); 
      String description = request.getParameter("description"); 
      //String image = request.getParameter("image"); 
      String category=request.getParameter("category"); 
      String unit=request.getParameter("unit"); 
      String units=request.getParameter("units"); 
      String price=request.getParameter("price"); 

      //byte[] b=null; 

      Part filePart=request.getPart("image"); 
      String filePath = filePart.getSubmittedFileName(); 
      File image = new File(filePath); 
      FileInputStream fis = new FileInputStream(image); 
     /*  
     try 
      { 
      //con=MyConnection.getConnection(); 
      //DiskFileItemFactory factory = new DiskFileItemFactory(); 

      //ServletFileUpload sfu = new ServletFileUpload(factory); 
      //List items = sfu.parseRequest(request); 

      //Iterator iter = items.iterator(); 

      //while (iter.hasNext()) 
      { 
       //FileItem item = (FileItem) iter.next(); 
       //if (!item.isFormField()) 
       { 
        //b = item.get(); 
       } 
      } 
      pst=con.prepareStatement("insert into menu(menu_name,description,image,category,unit,units,price) values(?,?,?,?,?,?,?)"); 
      pst.setString(1, name); 
      pst.setString(2, description); 
      pst.setBytes(3,b); 
      pst.setString(4, category); 
      pst.setString(5, unit); 
      pst.setString(6,units); 
      pst.setString(7,price); 
      pst.executeUpdate(); 
      System.out.println("inserted successfully"); 
     } 
     //catch (SQLException e) 
     { 
      // TODO Auto-generated catch block 
      //e.printStackTrace(); 
     } 
     //catch (FileUploadException e) 
     { 
      //System.out.println(e.getMessage()); 
      // TODO: handle exception 
     }*/ 

     response.setContentType("text/html;charset=UTF-8"); 
     try { 
      out.println("<!DOCTYPE html>"); 
      out.println("<html>"); 
      out.println("<head>"); 
      out.println("<title>Servlet TestServlet</title>");    
      out.println("</head>"); 
      out.println("<body>"); 
      out.println("<h1> Name : " +name+"</h1>"); 
      out.println("<h1> Desc : " +description+"</h1>"); 
      out.println("<h1> Category : " +category+"</h1>"); 
      out.println("<h1> Unit : " +unit+"</h1>"); 
      out.println("<h1> Units : " +units+"</h1>"); 
      out.println("<h1> Price : " +price+"</h1>"); 
      out.println("<h1> Image filePath : " +filePath+"</h1>"); 
      out.print(""); 
      out.println("</body>"); 
      out.println("</html>"); 
     }catch(Exception ex){ 

     }  

    } 

} 

運行它,自己去查。沒有什麼是零。

+0

其實我做了同樣的,你給我的解決方案,但它仍然給我空值,同時調用servlet名= null –

+0

@SwatiDhamdhere:只有名稱爲空或所有其他參數是空的? –

+0

只有nameis null –