如何将值从JSP页面传递到Servlet并保存在MySQL数据库中?

时间:2012-09-28 06:29:34

标签: mysql jsp servlets

我想在apache tomcat中上传文件,并使用JSP从文本字段中将数据保存在MySQL中。这样做,我无法将值从JSP页面传递给Servlet并保存在数据库中。 我该怎么做? 我尝试了以下几行代码: JSP:

<form action="UploadServlet" method="post"
          enctype="multipart/form-data">
        <input type="file" name="file" size="50" />
        <br />
        <input name="a" type="text"/>
        <br />
        <input type="submit" value="Upload File" />
    </form>

我还在Servlet中使用了以下几行代码:

的Servlet

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {

    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 10000 * 1024;
    private int maxMemSize = 5 * 1024;
    private File file;
    String gi;

    @Override
    public void init() {
        // Get the file location where it would be stored.
        filePath = getServletContext().getInitParameter("file-upload");        
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse            

response) throws ServletException, IOException {        
        // Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(request);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        gi =request.getParameter("a");
        if (!isMultipart) {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("D:\\Software\\apache-tomcat-7.0.29\\webapps\\Hello\\temp"));
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);
        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);
            // Process the uploaded file items
            Iterator i = fileItems.iterator();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    fi.write(file);
                    out.println("Uploaded Filename: " + fileName + "<br>");
                }
            }
        } catch (Exception ex) {
            out.println("Your file size should be less than 10 or equal to 10kb" + ex);
        }
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<h1>"+gi+"</h1>");
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webSiteTest", "root", "root");
                PreparedStatement stat = conn.prepareStatement("insert into abc(name) values (?)");
                stat.setString(1, gi);
                int aa = stat.executeUpdate();
                JOptionPane.showMessageDialog(null, "Database Connected Successfully.");
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Query Error!");
            } catch (ClassNotFoundException ee) {
                JOptionPane.showMessageDialog(null, "Database not Found!");
            }            
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        processRequest(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        //throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
        processRequest(request, response);
    }    
}

我该怎么办呢。

2 个答案:

答案 0 :(得分:0)

创建指向您在JSP中指定的文件的文件对象。

并在JSP中,

          request.setAttribute("file",fileObject);

并在Servlet中使用

获取该对象
          request.getAttribute("file");

尝试这个。它应该工作。

答案 1 :(得分:0)

要通过JSP / servlet发送文件,我们需要一个commonsio.jar文件,这很容易在谷歌中找到。现在将该jar文件放在tomcat文件夹的lib目录中,现在它可以工作。