Não consigo fazer login usando tabelas

2 respostas
E

Meus amigos,
Estou pegando um exemplo nas videoaulas que adquiri e tem uma classe que faz login no sistema, entretanto não mostra como fazer login pegando dados da tabela.
Ja pesquisei muito a procura disto e não achei, e as que achei não entendi, gostaria da ajuda de vcs para eu entender como conseguir fazer login usando os dados da tabela de funcionarios, neta tem os campos USUARIO e SENHA, abaixo ta exatamente como foi proposto na videoaula.

package br.com.prestcontas.main;

import org.openswing.swing.tree.java.OpenSwingTreeNode;
import java.util.*;
import org.openswing.swing.mdi.client.*;
import org.openswing.swing.util.client.*;
import org.openswing.swing.permissions.client.*;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import org.openswing.swing.mdi.java.ApplicationFunction;
import java.sql.*;
import org.openswing.swing.domains.java.Domain;
import org.openswing.swing.internationalization.java.*;
import org.openswing.swing.util.java.Consts;

/**
 * <p>Title: OpenSwing Demo</p>
 * <p>Description: Used to start application from main method:
 * it creates an MDI Frame app.</p>
 * <p>Copyright: Copyright (C) 2006 Mauro Carniel</p>
 * <p> </p>
 * @author Mauro Carniel
 * @version 1.0
 */
public class Menu implements MDIController, LoginController {

    private ClienteFachada clientFacade = null;
    private Connection conn = null;
    private Hashtable domains = new Hashtable();
    private String username = null;
    private Properties idiomas = new Properties();

    public Menu() {
        createConnection();
        clientFacade = new ClienteFachada(conn);

        Hashtable xmlFiles = new Hashtable();
        xmlFiles.put("EN", "recursos/Resources_en.xml");
        xmlFiles.put("IT", "recursos/Resources_it.xml");
        xmlFiles.put("PT_BR", "recursos/Resources_pt_br.xml");

        ClientSettings clientSettings = new ClientSettings(
                new XMLResourcesFactory(xmlFiles, false),
                domains);

        ClientSettings.BACKGROUND = "logovip.gif";
        ClientSettings.BACK_IMAGE_DISPOSITION = Consts.BACK_IMAGE_CENTERED;
        ClientSettings.TREE_BACK = "LogoAlterdata.jpg";  //<<======  PROCURAR IMAGEM DO MENU
        ClientSettings.VIEW_BACKGROUND_SEL_COLOR = true;
        ClientSettings.VIEW_MANDATORY_SYMBOL = true;
        ClientSettings.ALLOW_OR_OPERATOR = false;
        ClientSettings.INCLUDE_IN_OPERATOR = false;
        ClientSettings.SHOW_SCROLLBARS_IN_MDI = false;
        ClientSettings.FILTER_PANEL_ON_GRID = true;

        ClientSettings.getInstance().setLanguage("PT_BR");

        idiomas.setProperty("EN", "English");
        idiomas.setProperty("IT", "Italiano");
        idiomas.setProperty("PT_BR", "Português do Brasil");

        LoginDialog d = new LoginDialog(
                null,
                false,
                this,
                "Autenticação",
                "Login",
                'L',
                "Sair",
                'S',
                "Armazenar Informações",
                "Prestação de Contas",
                null,
                idiomas,
                "PT_BR");

    }

    /**
     * Method called after MDI creation.
     */
    public void afterMDIcreation(MDIFrame frame) {
        GenericStatusPanel userPanel = new GenericStatusPanel();
        userPanel.setColumns(12);
        MDIFrame.addStatusComponent(userPanel);
        //userPanel.setSize(100, 100);
        userPanel.setText(username);
        MDIFrame.addStatusComponent(new Clock());
    }

    /**
     * @see JFrame getExtendedState method
     */
    public int getExtendedState() {
        return JFrame.MAXIMIZED_BOTH;
    }

    /**
     * @return client facade, invoked by the MDI Frame tree/menu
     */
    public ClientFacade getClientFacade() {
        return clientFacade;
    }

    /**
     * Method used to destroy application.
     */
    public void stopApplication() {
        System.exit(0);
    }

    /**
     * Defines if application functions must be viewed inside a tree panel of MDI Frame.
     * @return <code>true</code> if application functions must be viewed inside a tree panel of MDI Frame, <code>false</code> no tree is viewed
     */
    public boolean viewFunctionsInTreePanel() {
        return true;
    }

    /**
     * Defines if application functions must be viewed in the menubar of MDI Frame.
     * @return <code>true</code> if application functions must be viewed in the menubar of MDI Frame, <code>false</code> otherwise
     */
    public boolean viewFunctionsInMenuBar() {
        return true;
    }

    /**
     * @return <code>true</code> if the MDI frame must show a login menu in the menubar, <code>false</code> no login menu item will be added
     */
    public boolean viewLoginInMenuBar() {
        return true;
    }

    /**
     * @return application title
     */
    public String getMDIFrameTitle() {
        return "Alterdata - Sistema para prestação de contas.";
    }

    /**
     * @return text to view in the about dialog window
     */
    public String getAboutText() {
        return "Alterdata - Sistema para prestação de contas.\n" +
                "\n" +
                "Copyright: Copyright (C) 2009 Filial Fortaleza\n" +
                "Autor: Elias@Fortaleza";
    }

    /**
     * @return image name to view in the about dialog window
     */
    public String getAboutImage() {
        return "about.jpg";
    }

    /**
     * @param parentFrame parent frame
     * @return a dialog window to logon the application; the method can return null if viewLoginInMenuBar returns false
     */
    public JDialog viewLoginDialog(JFrame parentFrame) {
        JDialog d = new LoginDialog(
                parentFrame,
                true,
                this,
                "Autenticação",
                "Login",
                'L',
                "Sair",
                'S',
                "Armazenar Informação",
                "Prestação de Contas",
                null,
                idiomas,
                ClientSettings.getInstance().getResources().getLanguageId());
        return d;
    }

    /**
     * @return maximum number of failed login
     */
    public int getMaxAttempts() {
        return 3;
    }

    /**
     * Method called by MDI Frame to authenticate the user.
     * @param loginInfo login information, like username, password, ...
     * @return <code>true</code> if user is correcly authenticated, <code>false</code> otherwise
     */
    public boolean authenticateUser(Map loginInfo) throws Exception {
        if ("CARLOS@FORTALEZA".equalsIgnoreCase((String) loginInfo.get("username")) &&
                "1".equalsIgnoreCase((String) loginInfo.get("password")) ||
                "ELIAS@FORTALEZA".equalsIgnoreCase((String) loginInfo.get("username")) &&
                "1".equalsIgnoreCase((String) loginInfo.get("password")) ||
                "CLAUDIANA@FORTALEZA".equalsIgnoreCase((String) loginInfo.get("username")) &&
                "1".equalsIgnoreCase((String) loginInfo.get("password")) ||
                "ODERLAN@FORTALEZA".equalsIgnoreCase((String) loginInfo.get("username")) &&
                "1".equalsIgnoreCase((String) loginInfo.get("password")) ||
                "GIUCIPE@FORTALEZA".equalsIgnoreCase((String) loginInfo.get("username")) &&
                "1".equalsIgnoreCase((String) loginInfo.get("password"))) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] argv) {
        new Menu();
    }

    /**
     * Method called by LoginDialog to notify the sucessful login.
     * @param loginInfo login information, like username, password, ...
     */
    public void loginSuccessful(Map loginInfo) {
        username = loginInfo.get("username").toString().toUpperCase();
        if (username.equals("ADMIN")) {
            ClientSettings.getInstance().setLanguage("EN");
        } else if (username.equals("ELIAS")) {
            ClientSettings.getInstance().setLanguage("PT_BR");
        } else if (username.equals("ALBERT")) {
            ClientSettings.getInstance().setLanguage("IT");
        } else ClientSettings.getInstance().setLanguage("PT_BR");

        MDIFrame mdi = new MDIFrame(this);

     //-------------------------------------------------
     //Preenche combo no formulário de Movimentação
    Domain orderStateDomain = new Domain("ORDERSTATE");
    orderStateDomain.addDomainPair("ESC","ESCRITÓRIO");
    orderStateDomain.addDomainPair("CLI","CLIENTE");
    domains.clear();
    domains.put(
      orderStateDomain.getDomainId(),
      orderStateDomain
    );
    //-------------------------------------------------


        //configura os botões da barra de ferramentas
        mdi.addButtonToToolBar("pessoas.png", "Cadastro de Pessoas");
        mdi.addButtonToToolBar("movimentacao.gif", "Movimentação");
        mdi.addButtonToToolBar("tipovisita.gif", "Tipos de Visitas");

        mdi.addButtonToToolBar("fornecedor.png", "Cadastro de Sistemas");
        mdi.addButtonToToolBar("banco.png", "Login");
        mdi.addButtonToToolBar("inquilino.png", "Cadastro de Pessoas");

        mdi.addSeparatorToToolBar();
        mdi.addSeparatorToToolBar();
        mdi.addButtonToToolBar("contrato.png", "Cadastro dos Contratos com Fornecedores");
        mdi.addSeparatorToToolBar();
        mdi.addSeparatorToToolBar();
        mdi.addButtonToToolBar("boleto.png", "Emissão de Boletos");
        mdi.addButtonToToolBar("gas.png", "Controle do Gás");
        mdi.addSeparatorToToolBar();
        mdi.addSeparatorToToolBar();
        mdi.addButtonToToolBar("pagar.png", "Contas a Pagar");
        mdi.addButtonToToolBar("receber.png", "Confirma Recebimentos");
        mdi.addButtonToToolBar("cheque.png", "Conciliação de Cheques");
        mdi.addButtonToToolBar("bancario.png", "Movimento Bancário");
        mdi.addSeparatorToToolBar();
        mdi.addSeparatorToToolBar();
        mdi.addButtonToToolBar("ata.png", "Controle de Atas");
        mdi.addButtonToToolBar("carta.png", "Cartas de Cobrança");
        mdi.addSeparatorToToolBar();
        mdi.addSeparatorToToolBar();
        mdi.addButtonToToolBar("sair.png", "Sair da Aplicação");
    }

    /**
     * @return <code>true</code> if the MDI frame must show a change language menu in the menubar, <code>false</code> no change language menu item will be added
     */
    public boolean viewChangeLanguageInMenuBar() {
        return true;
    }

    /**
     * @return list of languages supported by the application
     */
    public ArrayList getLanguages() {
        ArrayList list = new ArrayList();
        list.add(new Language("EN", "English"));
        list.add(new Language("IT", "Italiano"));
        list.add(new Language("PT_BR", "Portugês do Brasil"));
        return list;
    }

    /**
     * @return application functions (ApplicationFunction objects), organized as a tree
     */
    public DefaultTreeModel getApplicationFunctions() {
        DefaultMutableTreeNode root = new OpenSwingTreeNode();

        DefaultTreeModel model = new DefaultTreeModel(root);

        ApplicationFunction n1 = new ApplicationFunction("Cadastro", null);
        ApplicationFunction n2 = new ApplicationFunction("Movimento", null);

        ApplicationFunction n11 = new ApplicationFunction("Pessoas", "pessoas", null, "getPessoa");
        ApplicationFunction n12 = new ApplicationFunction("Sistemas", "sistema", null, "getSistema");
        //ApplicationFunction n13 = new ApplicationFunction("Bancos", "banco", null, "getLogin");
        ApplicationFunction n14 = new ApplicationFunction("Transportes", "transporte", null, "getTransporte");
        ApplicationFunction n15 = new ApplicationFunction(true);
        ApplicationFunction n16 = new ApplicationFunction("Tipos de Visita", "tipovisita", null, "getTipoVisita");
        //ApplicationFunction n17 = new ApplicationFunction("Contratos", "contrato", null, "getMovimentacao");

        //ApplicationFunction n21 = new ApplicationFunction("Lançamentos", null);
        //ApplicationFunction n211 = new ApplicationFunction("Emissao de Boletos", "boleto", null, "getBoleto");
        //ApplicationFunction n212 = new ApplicationFunction("Confirma Recebimentos", "receber", null, "getReceber");
        ApplicationFunction n21 = new ApplicationFunction("Movimentação", "movimentacao", null, "getMovimentacao");
        /*ApplicationFunction n23 = new ApplicationFunction("Controle do Gás", "gas", null, "getGas");
        ApplicationFunction n24 = new ApplicationFunction("Conciliação de Cheques", "cheque", null, "getCheque");
        ApplicationFunction n25 = new ApplicationFunction("Movimento Bancário", "bancario", null, "getBancario");
        ApplicationFunction n26 = new ApplicationFunction(true);
        ApplicationFunction n27 = new ApplicationFunction("Controle de Atas", "ata", null, "getAta");
        ApplicationFunction n28 = new ApplicationFunction("Cartas de Cobrança", "cobranca", null, "getCobranca");*/

        n1.add(n11);
        n1.add(n12);
        //n1.add(n13);
        n1.add(n14);
        n1.add(n15);
        n1.add(n16);
        //n1.add(n17);

        n2.add(n21);
        //n21.add(n211);
        //n21.add(n212);
        //n2.add(n22);
        /*n2.add(n23);
        n2.add(n24);
        n2.add(n25);
        n2.add(n26);
        n2.add(n27);
        n2.add(n28);*/

        root.add(n1);
        root.add(n2);

        return model;
    }

    /**
     * Create the database connection
     */
    private void createConnection() {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/alterdata?user=root&password=123456");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @return <code>true</code> if the MDI frame must show a panel in the bottom, containing last opened window icons, <code>false</code> no panel is showed
     */
    public boolean viewOpenedWindowIcons() {
        return true;
    }
}

2 Respostas

C

No próprio GUJ.

http://www.guj.com.br/posts/list/121584.java

Na linha 7 eh dado o driver a ser utilizado (nesse caso um MySQL)
Na linha 8 eh adiquirida uma conexao.
Na linha 10 é feita a query para captar a informacao do banco.
Na linah 11 é executada a consulta.
E da linha 13 a 30 é feita a mágica de autenticação, onde é percorrido o resultado da consulta e comparado ao login do banco com o passado pelo usuário e a senha do banco com a passada pelo usuário.

E

Na verdade nao era isso que eu estava perguntando, acho que me expressei mal, porem um professor de java me ajudou e vou postar para vcs.

===================== /** * Method called by MDI Frame to authenticate the user. * @param loginInfo login information, like username, password, ... * @return <code>true</code> if user is correcly authenticated, <code>false</code> otherwise */ public boolean authenticateUser(Map loginInfo) throws Exception { PreparedStatement ps = null; try { ps = conn.prepareStatement("select * from funcionario where login=? and senha=?"); ps.setString(1, (String) loginInfo.get("username")); ps.setString(2, (String) loginInfo.get("password")); ResultSet rs = ps.executeQuery(); return rs.next(); } catch (Exception ex) { // poderia reportar o erro ocorrido aqui return false; } finally { if (ps != null) ps.close(); } } =====================

Obrigado pela atenção.

Criado 19 de janeiro de 2010
Ultima resposta 19 de jan. de 2010
Respostas 2
Participantes 2