Как можно передать пользовательские данные в MySQL?

Класс SignUpServlet запоминает введенные пользователем данные в UserProfile. Каким образом их следует извлечь и передать запросом в БД?

public class DBService extends AccountService {
    private final Connection connection;
    String login;
    String pass;
    String secpass;

    public DBService() {
        this.connection = getMysqlConnection();
    }

    public UsersDataSet getUser(long id) throws DBException {
        try {
            return (new UsersDAO(connection).get(id));
        } catch (SQLException e) {
            throw new DBException(e);
        }
    }


    public long addUser() throws DBException {
        try {
            Statement stmt = connection.createStatement();
            connection.setAutoCommit(false);
            UsersDAO dao = new UsersDAO(connection);
            addNewUser(new UserProfile(login, pass, secpass));

            stmt.executeUpdate ("INSERT INTO userstable (login, pass, secpass) values ('" + login + "', '" + pass + "' ,  '" + secpass + "' )");
            return dao.getUserId(login);
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ignore) {
            }
            throw new DBException(e);
        } finally {
            try {
                connection.setAutoCommit(true);
            } catch (SQLException ignore) {
            }
        }
    }

    public void cleanUp() throws DBException {
        UsersDAO dao = new UsersDAO(connection);
        try {
            dao.dropTable();
        } catch (SQLException e) {
            throw new DBException(e);
        }
    }

    public void printConnectInfo() {
        try {
            System.out.println("DB name: " + connection.getMetaData().getDatabaseProductName());
            System.out.println("DB version: " + connection.getMetaData().getDatabaseProductVersion());
            System.out.println("Driver: " + connection.getMetaData().getDriverName());
            System.out.println("Autocommit: " + connection.getAutoCommit());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getMysqlConnection() {
        try {
            DriverManager.registerDriver((Driver) Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance());
            StringBuilder url = new StringBuilder();

            url.
                    append("jdbc:mysql://").        //db type
                    append("localhost:").           //host name
                    append("3306/").                //port
                    append("users?").          //db name
                    append("user=root&").          //login
                    append("password=pass");       //password

            System.out.println("URL: " + url + "\n");

            Connection connection = DriverManager.getConnection(url.toString());

            return connection;


        } catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

}
public class UserProfile {
private final String login;
private final String pass;
private final String secpass;

 public UserProfile(String login, String pass, String secpass) {
    this.login = login;
    this.pass = pass;
    this.secpass=secpass;
}





public String getLogin() {
    return login;
}

public String getPass() {return pass;
}

}


public class SignUpServlet extends HttpServlet {

    private final AccountService accountService;



    public SignUpServlet(AccountService accountService) {
        this.accountService = accountService;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException, IOException {

        String sessionId = request.getSession().getId();
        String login = request.getParameter("login");
        String pass = request.getParameter("password");
        String secpass = request.getParameter("secpass");
        UserProfile profile = accountService.getUserByLogin(login);
        accountService.addNewUser(new UserProfile(login, pass, secpass));
        accountService.addSession(request.getSession().getId(), profile);
        }
    }


public class UsersDAO {

    private Executor executor;

    public UsersDAO(Connection connection) {
        this.executor = new Executor(connection);

    }

    public UsersDataSet get(long id) throws SQLException {
        return executor.execQuery("SELECT * FROM userstable where id=" + id, result -> {
            result.next();
            return new UsersDataSet(result.getInt(1), result.getString(2));
        });
    }


    public long getUserId(String login) throws SQLException {
      return executor.execQuery("SELECT * FROM userstable where login='" + login + "'", result -> {
            result.next();
            return result.getLong(1);
        });

    }

    public void dropTable() throws SQLException {
        executor.execUpdate("drop table users");
    }
}
public class Main {


    public static void main(String[] args) throws Exception {
        DBService dbService = new DBService();
        dbService.printConnectInfo();
        try {
            long userId = dbService.addUser();
            System.out.println("Added user id: " + userId);

            UsersDataSet dataSet = dbService.getUser(userId);
            System.out.println("User data set: " + dataSet);

            dbService.cleanUp();
        } catch (DBException e) {
            e.printStackTrace();
        }
        AccountService  accountService = new AccountService();


        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        context.addServlet(new ServletHolder(new SignInServlet(accountService)), "/signin");
        context.addServlet(new ServletHolder(new SignUpServlet(accountService)),"/signup");



        RewriteHandler rewriteHandler = new RewriteHandler();
        rewriteHandler.addRule(new RewriteRegexRule("/main", "/index.html"));

        ResourceHandler resource_handler = new ResourceHandler();
        resource_handler.setResourceBase(".idea/templates");


        HandlerList handlers = new HandlerList();
       handlers.setHandlers(new Handler[]{resource_handler, context});
        handlers.setHandlers(new Handler[]{rewriteHandler, resource_handler, context});
        Server server = new Server(8080);
        server.setHandler(rewriteHandler);
        server.setHandler(handlers);

        server.start();
        java.util.logging.Logger.getGlobal().info("Server started");
        server.join();
    }
}

Ответы (0 шт):