从同一servlet中的文本字段上载图像和信息

时间:2014-05-05 02:26:25

标签: html jsp servlets

这是我第一次使用JSP和servlet。我的JSP中有一个表单,其中包含产品名称,描述等的文本输入,以及上传图像的字段。一切都存储在数据库中(但只有图像路径)。我在网上搜索了如何实现图像的东西,我终于让它工作了,但现在它不会从文本字段中读取信息。也就是说,我的变量是空的或null,即使它们应该从正确的参数中获取。

这是我的servlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
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;

public class AgregaProd extends HttpServlet{
    public void doPost(HttpServletRequest request,HttpServletResponse response){
        String nombre = request.getParameter("nombre");
        String precio = request.getParameter("precio");
        String catalogo = request.getParameter("catalogo");
        String descripcion = request.getParameter("descripcion");
    try{
        String fileName="";
        String imagen="";
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

         if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {

                FileItem imageFile = (FileItem) iterator.next();
                if(imageFile.getSize() > 100000){
                    return ;
                }
                if (!imageFile.isFormField()) {
                    fileName = imageFile.getName();
                    String fileBase = getServletContext().getInitParameter("IMAGE_FILEBASE");
                    File filePath  = new File(fileBase  + File.separator);
                    if (!filePath.exists()) {
                        boolean status = filePath.mkdirs();
                    }
                    File uploadedFile = new File(filePath + "/" + fileName);
                    imageFile.write(uploadedFile);
                    imagen=getServletContext().getInitParameter("imgsd")+"ComprasCool/imagenes/"+fileName;
                }
            }
        }

        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost/ComprasCool";
        Connection con = DriverManager.getConnection(url,"root","jkDuhx+32");

        Statement stat = con.createStatement();

        ResultSet rs = stat.executeQuery("SELECT * FROM Producto");
        RequestDispatcher disp = getServletContext().getRequestDispatcher("/agregarproducto.jsp");

        int ide = 1;
        int idc = 0;

        switch(catalogo){
            case "hogar":
                idc=1;
                break;

            case "solares":
                idc=2;
                break;

            case "electronicos":
                idc=3;
                break;

            case "memorias":
                idc=4;
                break;

            case "accesorios":
                idc=5;
                break;
        }
        if(!rs.next()){
            stat.executeUpdate("INSERT INTO Producto VALUES (\"" + ide + "\",\"" + nombre + "\",\"" + descripcion + "\"," + precio + ",\"" + imagen + "\",\"" + idc + "\");");
            disp = getServletContext().getRequestDispatcher("/exito.jsp");
        } else {
            rs.last();
            ide=rs.getInt("idProducto")+1;
            stat.executeUpdate("INSERT INTO Producto VALUES (\"" + ide + "\",\"" + nombre + "\",\"" + descripcion + "\"," + precio + ",\"" + imagen + "\",\"" + idc + "\");");
            disp = getServletContext().getRequestDispatcher("/exito.jsp");
        }

        stat.close();
        con.close();

        if(disp!=null){
            disp.forward(request,response);
        }

    }catch(Exception e){
        e.printStackTrace();
    }
}
}

这是我的JSP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Compras Cool</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<div id="header">
<div id="logo"><a href="index.jsp"><img src="logo.gif" width="380" height="84" /></a>
</div>
<div id="search">
 <form id="form1" name="form1" method="post" action="./buscar">
   <input type="text" name="searchbar" class="searchbar" id="searchbar"/>
   <input type="submit" name="searchbtn" class="searchbtn" id="searchbtn" value="Buscar" />
 </form>
  </div>
    <div id="userstuff"><a href="admin.jsp">logout</a>
</div>
<div id="nav"><a href="./hogarAdmin" target="_self" class="nav_link">Hogar</a> <a href="./solaresAdmin" target="_self" class="nav_link">Solares</a> <a href="./electronicosAdmin" target="_self" class="nav_link">Electronicos</a> <a href="./memoriasAdmin" target="_self" class="nav_link">Memorias</a> <a href="./accesoriosAdmin" target="_self" class="nav_link">Accesorios</a><a href="ordenes.jsp" target="_self" class="nav_link">Ordenes</a></div>
<div id="content">
  <div id="registro">
  <h1>Nuevo producto</h1>

  <form id="form2" name="form2" method="POST" action="./registraProducto" runat="server" enctype="multipart/form-data">
    <p>
      <label>Nombre:&nbsp;&nbsp;&nbsp;
        <input type="text" name="nombre" id="textfield4" size="20" />
      </label>
</p>
<p>
  <label>Precio:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="text" name="precio" id="textfield6" size="20"/>
  </label>
</p>
<p>
  <label>Catalogo:&nbsp;&nbsp;&nbsp;&nbsp;</label>
    <select name="catalogo" id="select" class="select">
      <option value="hogar">Hogar</option>
      <option value="solares">Solares</option>
      <option value="electronicos">Electronicos</option>
      <option value="memorias">Memorias</option>
      <option value="accesorios">Accesorios</option>
    </select>
</p>
<label>Descripcion:</label><p>
<textarea name="descripcion" class="des"></textarea>
<p><label>Imagen:&nbsp;&nbsp;&nbsp;&nbsp;</label>
<input type="file" name="fileName" value="" accept="image/*" runat="server">
<p></p>
<p align="right">
  <input name="registrobtn" type="submit" class="loginbtn" value="Agregar" />    
</form>
  </div>
</div>
<div id="footer">&copy;Compras Cool 2014
<p>Acerca<font face="Arial"> | </font><a href="contacto.jsp">Contacto</a><font face="Arial"> | </font>Terminos y condiciones</p>
</div>
</body>

</html>

提前致谢!!

1 个答案:

答案 0 :(得分:0)

使用FileItem#getFieldName()获取输入字段的名称,使用FileItem#getString()获取输入字段的值。

<强>解决方案:

创建两个实用程序方法,一个用于常规输入字段,另一个用于文件输入字段数据。像:

// Process a regular form field
private void processFormField(FileItem item){
  if (item.isFormField()) {
     String name = item.getFieldName(); 
     String value = item.getString();
  }
}

// Process a file upload
private void processUploadedFile(FileItem imageFile){
   if (!imageFile.isFormField()) {
      //your existing file upload code.
   }
}

然后,在while循环中使用上面的方法来获取如下数据:

while (iterator.hasNext()) {
FileItem item = iterator.next();

    if (item.isFormField()) {
        processFormField(item);
    } else {
        processUploadedFile(item);
    }
}

Source