Home>

The program I want to create this time is Java (Servlet&jsp)
Prepare a screen where you can upload text files as WEB,
Read the above text file with the JAVA program on the server side
It is a program that saves the contents in the DB according to a series of rules and returns the completion screen to the client.

For the environment, install Apache, Tomcat, MySQL on a Linux server (VPS),
The created Servlet and jsp files are placed in Tomcat.

If I can connect to the DB, I'm trying to display an output that informs me of success.
Only a clean screen is returned.
Corresponding source code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet ("/ MainServlet")
@MultipartConfig (maxFileSize = 20971520, maxRequestSize = 20971520, fileSizeThreshold = 1048576, location = "/opt/apache-tomcat-8.5.61/temp")
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = request.getRequestDispatcher ("/jsp/input.jsp");
        dispatcher.forward (request, response);}
    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType ("text/html;charset = UTF-8");
        PrintWriter out = response.getWriter ();
        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc: mariadb: // localhost/upload_db";
        String user = "****";
        String password = "****";
        String insertSql = "INSERT INTO` upload_file` (` contents`) VALUES (?)";
        Part part = request.getPart ("uploadFile");
        String fileName = getFileName (part);
        String filePath = "/ uploaded";
        File uploadDir = mkdirs (filePath);
        part.write (getServletContext (). getRealPath (uploadDir.getPath () + "/" + fileName));
        File file = new File (getServletContext (). getRealPath (uploadDir.getPath () + "/" + fileName));
        FileReader fileReader = new FileReader (file);
        @SuppressWarnings ("resource")
        BufferedReader bufferedReader = new BufferedReader (fileReader);
        String data = bufferedReader.readLine ();
        while ((data = bufferedReader.readLine ())! = null) {
            try {
                 Class.forName ("org.mariadb.jdbc.Driver"). newInstance ();
                 out.println ("Successfully loaded driver<br>");
                 conn = DriverManager.getConnection (url, user, password);
                 out.println ("The database connection was successful<br>");
                 ps = conn.prepareStatement (insertSql);
                  ps.setString (1, data);
                  ps.executeUpdate ();
                conn.commit ();
                out.println ("Saved the uploaded text in the database<br>");
                } catch (ClassNotFoundException e) {
                    out.println ("ClassNotFoundException:" + e.getMessage ());
                } catch (SQLException e) {
                    out.println ("SQLException:" + e.getMessage ());} catch (Exception e) {
                    out.println ("Exception:" + e.getMessage ());
                }
            }
          }
       /**
         * Creating a directory
         * /
        private File mkdirs (String filePath) {
            File uploadDir = new File (filePath);
            uploadDir.mkdirs ();
            return uploadDir;
        }
       /**
         * Get file name
         * /
        private String getFileName (Part part) {
        String name = null;
        for (String dispotion: part.getHeader ("Content-Disposition"). split (";")) {
            if (dispotion.trim (). startsWith ("filename")) {
                name = dispotion.substring (dispotion.indexOf ("=") + 1) .replace ("\" "," "). Trim ();
                name = name.substring (name.lastIndexOf ("\\") + 1);
                break;
            }
        }
        return name;
        }
}
What I tried

I don't even know what to try.
Please help me.

Supplementary information (FW/tool version, etc.)

Please provide more detailed information here.

  • Answer # 1

    [Java&Tomcat] Get form data from Servlet (with sample code)
    Or
    Getting Started with Servlets/JSPs on Let's Programming Sites ›Database Connections It will be completed if you integrate it into the expected processing while checking the execution of each operation by referring to the addition of data (INSERT).

Related articles