2016-05-30 68 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 –