User control in java [closed]

-2

I am developing an electronic banking as a final project for the university, my project consists of the following frames:

LogIn
Estado de cuenta
Info de cuenta
Registros
funciones

As additional data all fields are stored in a database mysql , where functions shows you account status and account information, account status should your card number and the available balance and account info shows the data related to your account, such as first name, last name, city, etc., until now I have configured the login frame since it compares the data inside the database to access the function frame where it allows you to access the aforementioned frames.

My problem is that I can not find the way to show the necessary data depending on the session with which it starts, for example user 12 has $ 100 in his account, this information is what should be shown in the account statement frame. I know the query for mysql since I have created the database with 3 related tables to be able to show the information, which is not like having the control of the users.

    
asked by Hugo Costilla 16.11.2017 в 10:55
source

2 answers

2

Although the answer is not exactly what you expect, I pass you a mini example of servlet sessions and in the end how you could apply it to Swing.

Although the steps are more complex keep this question for later that surely you will see servlet at the time, however as I say there are ways to emulate behaviors to swing and in the end I will try to emulate this same swing in shape simpler and proposing ideas.

How Servlets would work

First of all in the package that has the entities we declare for example the Client Class:

As you will see, it has an empty constructor and another one with attributes, we have the vacuum in case we want to create a client object and only set some specific data as it will happen a little later.

    package com.soa.entities;

    public class Client {

        private int id;
        private String name;
        private double savings;

        public Client() {

        }

        public Client(int id, String name, double savings) {
            this.id = id;
            this.name = name;
            this.savings = savings;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public double getSavings() {
            return savings;
        }

        public void setSavings(double savings) {
            this.savings = savings;
        }

    }

Then we create a class of connection to the DB, since I am going to show you how to rescue the same data from one page to the other by a veriable one of Session and also by persisted data in a DB. Two very different things, however the last one is the one that most resembles what you want to do in swing

    package com.soa.dao;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;

    public class ConnectionStackOverflow {

        private final static String user = "root";
        private final static String password = "";

        public static Connection getConexion() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/homebanking" , user, password);
            return connection;
        }

        public static void closeConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
            getConexion().close();
        }
    }

Once the connection is made, you should create a DB in mysql called homebanking and a table with four columns:

id: int A_I, name: Varchar 20, lastname Varchar 20, savings: Double;

Next we create a controller class of what we do with the client and the DB.

I understand that this is sure to be basic Chinese at first but you have to see it patiently and deglosarlo a bit.

    package com.soa.controllers;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;

    import com.soa.dao.ConnectionStackOverflow;
    import com.soa.entities.Client;

    public class AccountController {

        /* Método para insertar un cliente a la DB */
        public static void insertClient(String name, String lastname, double savings) {
            Connection connection = null;
            /* Intentamos conectarnos */
            try {
                connection = ConnectionStackOverflow.getConexion();

                /* Si no es nula que entre al método que nos facilita realizar la insercción */
                if (connection != null) {
                    PreparedStatement ps;
                    String sql = "INSERT INTO accounts(name, lastname, savings) VALUES(?,?,?)";
                    ps = connection.prepareStatement(sql);
                    ps.setString(1, name);
                    ps.setString(2, lastname);
                    ps.setDouble(3, savings);
                    ps.executeUpdate();
                    ps.close();
                    System.out.println("Query executed");
                } else {
                    System.out.println("Connection appears to be null");
                }
            } catch (Exception error) {
                System.out.println("Cannot even connect");
                error.getMessage();
                error.printStackTrace();
            }
        }

        /*
         * Método para retornar un cliente por su id , este es que seguramente se usaría
         * en una app de Escritorio, llegando el id por un campo hidden
         */
        public static Client retriveClient(int id) {
            Connection connection = null;

            String name = null;
            double savings = 0;
            Client client = null;

            try {
                connection = ConnectionStackOverflow.getConexion();

                if (connection != null) {
                    Statement st;
                    String sql = "SELECT * FROM accounts WHERE id=" + id;
                    st = connection.createStatement();
                    ResultSet rs = st.executeQuery(sql);

                    /*
                     * Mientras haya un resultado en la tabla le decimos que nos lo traiga y que a
                     * su vez grabe las variables recuperadas en name y savings, y por último lo
                     * agregamos a un cliente nuevo
                     */
                    while (rs.next()) {
                        name = rs.getString("name");
                        savings = rs.getDouble("savings");
                        client = new Client(id, name, savings);
                    }
                    /* Lo probamos por consola para ver si funcionó */
                    System.out.println(client.getSavings());
                    System.out.println("Query executed");
                } else {
                    System.out.println("Connection appears to be null");
                }
            } catch (Exception error) {
                System.out.println("Cannot even connect");
                error.getMessage();
                error.printStackTrace();
            }
            return client;
        }

        /*
         * Esta consulta no es recomendada ya que lo ideal es realizar la consulta sobre
         * el id y en este caso lo estoy haciendo sobre el name y lastname, va a ser
         * untema tuyo como solucionarlo
         */
        public static double getPersistedSavings(String name, String lastname) {
            Connection connection = null;
            double savings = 0;
            Client client = null;
            try {
                connection = ConnectionStackOverflow.getConexion();
                /*  Si la conexión no es nula entonces que pase al métodos de averiguación de datos */
                if (connection != null) {
                    Statement st;
                    String sql = "SELECT savings FROM accounts WHERE name='" + name + "' AND lastname='" + lastname + "' ";
                    st = connection.createStatement();
                    ResultSet rs = st.executeQuery(sql);

                    /*  Sólo queremos los savings o saldo, usamos el constructor vacío y le seteamos el valor recuperado    */
                    while (rs.next()) {
                        savings = rs.getDouble("savings");
                        client = new Client();
                        client.setSavings(savings);
                    }
                    System.out.println(client.getSavings());
                    System.out.println("Query executed");
                } else {
                    System.out.println("Connection appears to be null");
                }
            } catch (Exception error) {
                System.out.println("Cannot even connect");
                error.getMessage();
                error.printStackTrace();
            }
            return savings;
        }

    }

Servlets in gral go in another package and you have to declare yes or yes in the WEB-INF / web.xml file later I put it also. We will have two, one to insert Clients to the DB and creating sessions and one to retrieve from the DB as well as making a data handrail between sessions.

    package com.soa.servlets;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    import com.soa.controllers.AccountController;

    public class InsertClientServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

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

            try {

                /* Recuperamos los datos de los inputs del jsp */
                String name = request.getParameter("name");
                String lastname = request.getParameter("lastname");
                String savings = request.getParameter("savings");

                /* Parseamos el String y lo pasamos a double */
                double doubleSavings = Double.parseDouble(savings);

                /* LLamamos al método que inserta los datos a la DB */
                AccountController.insertClient(name, lastname, doubleSavings);

                /*
                 * Además de haberlo insertado creamos una session y le agremos los siguientes
                 * atributos, name, lastname, savings
                 */
                HttpSession session = request.getSession(false);
                session.setAttribute("name", name);
                session.setAttribute("lastname", lastname);
                session.setAttribute("savings", doubleSavings);

                /*
                 * Cuando todo termina que nos derive a otra web donde vamos a consultar los
                 * savings por datos persistidos y por pasamanos de sessiones
                 */
                getServletConfig().getServletContext().getRequestDispatcher("/querySavings.jsp").forward(request, response);

            } catch (Exception error) {
                error.getMessage();
                error.printStackTrace();
            }

        }

    }

The index.jsp file where the client input form goes to the DB

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>

    <script type="text/javascript">

        function send() {
            var frm = document.frmInsertClient;
            frm.submit();
        }
    </script>

    <body>
        <h1>Insertar Cliente</h1>

        <form action="InsertClientServlet" method="get" name="frmInsertClient">
            <table>
                <tr>
                    <td><label>Nombre: </label></td>
                    <td><input type="text" name="name" /></td>
                </tr>
                <tr>

                    <td><label>Apellido: </label></td>
                    <td><input type="text" name="lastname" /></td>
                </tr>
                <tr>
                    <td><label>Saldo: </label></td>
                    <td><input type="number" name="savings" /></td>
                </tr>
                <tr>
                    <td><input type="button" value="boton" onclick="send()" /></td>
                </tr>
            </table>
        </form>

    </body>
    </html>

The second Servlet where we will process the data we received from the first

    package com.soa.servlets;

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    import com.soa.controllers.AccountController;

    public class QuerySavingsServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

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

            try {
                /* Grabados en session */
                HttpSession session = request.getSession(false);
                PrintWriter pw = response.getWriter();
                pw.println("Este saldo es que escribimos en la pantallas pasadas y que lo grabamos en memoria Session");
                pw.println("******************************   " + session.getAttribute("savings")
                        + "   **************************************");

                /* Consultados en la Base de Datos, información persistida */
                String name = (String) session.getAttribute("name");
                String lastname = (String) session.getAttribute("lastname");
                double persistedSavings = AccountController.getPersistedSavings(name, lastname);
                pw.println("Este saldo es el que está persistido en la DB y que consultamos por medio una consulta");
                pw.println("******************************   " + persistedSavings
                        + "   **************************************");

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

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

        }

    }

The querySavings.jsp file where we will have a form that connects to the previous servlet and queries the DB and also returns the value recorded in session.

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ page import="com.soa.entities.Client"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Averiguar saldo</title>
    </head>

    <script type="text/javascript">

        function send() {
            var frm = document.frmSavings;
            frm.submit();
        }
    </script>
    <body>

        <h1>Averiguar saldo</h1>

        <%
            session.getAttribute("name");
            session.getAttribute("savings");
            session.getAttribute("lastname");
        %>
    Esta es la sessión de <% out.print(session.getAttribute("name")); %><br>

        <form action="QuerySavingsServlet" method="get" name="frmSavings">
            <input type="hidden" name="id" value=<% out.print(session.getAttribute("name")); %> /> <br> 
            <input type="text" value=<% out.print(session.getAttribute("savings")); %>> <input type="button" value="Averiguar Saldo" onclick="send()" />
        </form>
    </body>
    </html>

Web.xml configuration file where the two servlets are declared.

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>StackOverflowWeb</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
        <servlet>
            <servlet-name>InsertClientServlet</servlet-name>
            <servlet-class>com.soa.servlets.InsertClientServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>InsertClientServlet</servlet-name>
            <url-pattern>/InsertClientServlet</url-pattern>
        </servlet-mapping>

        <servlet>
            <servlet-name>QuerySavingsServlet</servlet-name>
            <servlet-class>com.soa.servlets.QuerySavingsServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>QuerySavingsServlet</servlet-name>
            <url-pattern>/QuerySavingsServlet</url-pattern>
        </servlet-mapping>
    </web-app>

This is the final result, two data, one session in memory and another persisted, we will take the form in which we recover the persisted for Swing.

How to do something similar in Swing

We create a first screen, which can do several things, such as reusing the code we use to insert into the DB but using the TextField, or otherwise directly load the DB and use that screen to recover the data.

For all inserts to work well, you have to follow some guidelines and use some classes or interfaces such as PreparedStatement or Statement and the Resultset for the return of data. Above I made an insertion and two data retrievals with their methods.

        package com.soa.view;

        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;

        import javax.swing.JButton;
        import javax.swing.JFrame;
        import javax.swing.JPanel;
        import javax.swing.JTextField;

        import com.soa.controllers.ClientController;

        public class LoginFrame implements ActionListener {

            /*
             * Hacemos un primer ventana donde el primer input es el nombre, el segundo es
             * apellido y el tercero es id en disabled
             */
            public JFrame jframe;
            public JPanel jpanel;
            public JTextField text1, text2, text3;
            public JButton jbutton;

            public LoginFrame() {

                jframe = new JFrame();
                jpanel = new JPanel();

                text1 = new JTextField(20);
                text2 = new JTextField(20);
                text3 = new JTextField(3);
                text3.disable();

                jbutton = new JButton("Consultar");

                jframe.add(jpanel);
                jpanel.add(text1, "Nombre");
                jpanel.add(text2, "Saldo");
                jpanel.add(text3, "id");
                jpanel.add(jbutton);

                jframe.setBounds(100, 100, 250, 150);
                jframe.setVisible(true);

                /*
                 * creas un action listener para que a su vez rescate información persistida en
                 * la DB
                 */
                this.jbutton.addActionListener(this);

            }

            @Override
            public void actionPerformed(ActionEvent obj) {
                if (obj.equals(jbutton)) {

                    /* Esta clase no existe en mi proyecto pero la estoy proponiendo junto con el métodode insercción   */
                    ClientController.insertClientToDB(text1, text2);
                    /* Los datos se van a insertar si está bien hecho el método y la tabla  */

                    /*Creamos otra ventana pero esta vez de consulta */
                    QueryJframe qf = new QueryJFrame();

                    /* y cerramos la anterior */
                    jframe.dispose();
                }

            }

        }

Now we go to Create the other Frame that we are going to put QueryFrame, in it we will recover the data with a Statement and ResultSet, activated by a button and the ActionListener interface.

I repeat that this swing project I have not done in my Eclipse, I'm doing it on the fly and proposing ideas, therefore if they copy and paste some other error and / or warning may appear.

        package com.soa.view;

        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;

        import javax.swing.JButton;
        import javax.swing.JFrame;
        import javax.swing.JLabel;
        import javax.swing.JPanel;
        import javax.swing.JTextField;

        import com.soa.controllers.ClientController;

        public class QueryJframe implements ActionListener{


            /*
             * Hacemos un primer ventana donde el primer input es el nombre, el segundo es
             * apellido, vamos autilizar los mismos para recuperar el dato savings de la DB
             */
            public JFrame jframe;
            public JPanel jpanel;
            public JTextField text1, text2;
            public JButton jbutton;
            public JLabel jlabel;

            public QueryJframe() {

                jframe = new JFrame();
                jpanel = new JPanel();

                text1 = new JTextField(20);
                text2 = new JTextField(20);
                jlabel = new JLabel("Acá va a estar el reultado");


                jbutton = new JButton("Savings");

                jframe.add(jpanel);
                jpanel.add(text1, "Nombre");
                jpanel.add(text2, "Saldo");
                jpanel.add(jbutton);


                jframe.setBounds(100, 100, 150, 250);
                jframe.setVisible(true);

                /*
                 * creas un action listener para que a su vez rescate información persistida en
                 * la DB
                 */
                this.jbutton.addActionListener(this);

            }

            @Override
            public void actionPerformed(ActionEvent obj) {
                if (obj.equals(jbutton)) {
                    /* Se la asinamos a una nueva variable double que tomará el valor que hay en la DB */
                    /* Esta clase no existe en mi proyecto pero la estoy proponiendo junto con el métodode insercción, este mismo deberìa ser un método que devuelva un double  */
                    double savings = ClientController.getClientSavings(text1, text2);

                    /* setText() solo acepta Strings por ende tenemos que pasar de double a String */
                    String strSavings = Double.toString(savings);

                    jlabel.setText(strSavings);
                }

            }

        }

In conclusion to all this is that we can do through the fields of JText we can enter data and another method brings the DB, or if there is a hidden field that I do not remember if there is, if there is no JTextField and we apply a disabled (), that takes the value of the id that we want to consult the balance and we create the corresponding query. It is simpler for Swing but in turn it seems less complete, however servlets is too complex with many ideas and twists, I repeat that my intention is that you can see structurally the two cases.

    
answered by 16.11.2017 в 20:31
0

I would establish a field of type "permission" or "credentials" so that, depending on the type of user, the fields you want will be shown depending on the account. In my case, for example, I made a control application for a school.

The accounts type "admin" accessed everything, those of type "teacher" could not register other teachers but students, and accounts type "student" could only see results. That controlled by a "credential" field with values 0, 1 or 2. Each field is a type of account.

I do not know if I have helped you and I hope I have understood your doubt.

Edit: Obviously, but in the LogIn screen you have to open the connection to the database and launch the access data against it, with a username that is stored in the user table and the field of type of account.

    
answered by 16.11.2017 в 12:46