简体   繁体   中英

How can I pass value from JSP page to Servlet and save in MySQL database?

I want to upload a file in apache tomcat and save data in the MySQL from text field using JSP. On doing so, I could not pass the value from JSP page to Servlet and save in Database. How can I do it? I tried the following lines of code: 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>

And also I used the following lines of code in 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);
    }    
}

How can I do this.

Create file object that points to a file specified by you in JSP.

and in JSP do,

          request.setAttribute("file",fileObject);

and in Servlet get that object using

          request.getAttribute("file");

try this.it should work.

To send a file through a JSP/servlet we need a commonsio.jar file and this will be easily found in the google. Now place that jar file in the lib directory of the tomcat folder and Now it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM