How to use jQuery + Ajax with Java EE

Asked

Viewed 860 times

2

I’m creating a connection to the Java database like this:

try{
        Class.forName("org.postgresql.Driver");
        Connection con = DriverManager.getConnection("jdbc:postgresql://localhost/projeto","postgres","754753"); 
        if(request.getParameter("user") != null)
        {
            //caminho para chegar até a tabela no BD
            Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ResultSet rs = st.executeQuery("select * from login where log_usuario = '"+
                    request.getParameter("user")+"' and log_senha = '"+
                    request.getParameter("pass")+"'");

            if(rs.next())
                //response.sendRedirect("paginas/home.jsp");
            else
                out.println("Não Logado");
        }

    }
    catch(ClassNotFoundException ClassError){
        out.println("Driver não encontrado "+ClassError);
    }
    catch(SQLException SQLError){
        out.println("Erro de conexão com o banco de dados");
    }

I want to send it to ajax to validate with the $.ajax({});.

Within the success I want to have 3 conditions that would be:

  1. enter your user and password
  2. invalid username or password
  3. login done, please wait...

Sort of like this:

$('form').submit(function(){
            var login = $(this).serialize();
            $.ajax({
                url:
                data:
                type:
                success: function(resposta){
                    if(resposta == 'erroempty'){
                        $('.msg').empty().hmtl('<p class="aviso">Informe seu usuário e senha!</p>').fadeIn('slow');
                    }else if(resposta == 'errosenha'){
                        $('.msg').empty().hmtl('<p class="erro">Erro ao logar! Dados não conferem!</p>').fadeIn('slow');
                    }else if(resposta == 'success'){
                        $('.msg').empty().hmtl('<p class="sucesso">Login efetuado, aguarde...</p>').fadeIn('slow');
                    }

                },
                beforeSend: function(){
                    $('.loginbox h1 img').fadeIn('fast');  
                },
                complete: function(){
                    $('.loginbox h1 img').fadeOut('fast');  
                }


            });

            return false;

        });

How do I get Java to pass the 3 information (erroempty, erroneous password and Success) and what I would put in url, data and type?

1 answer

1

So your problem is conceptual, you need to understand how this requests engine works, you could use JSON to return several parameters on the page.

Example of JSON use in your case:

{
  "erroempty": {
    "Msg": "Informe seu usuário e senha!"
  },
  "errosenha": {
    "Msg": "Erro ao logar! Dados não conferem!"
  },
  "success": {
    "Msg": "Login efetuado, aguarde..."
  }
}

Configuring the request

 url:  destino da request
    data: Conjuntos de parâmetros que vão ser enviados via get/post
    type: tipo da request get/post

in your case!

url: Nome da classe principal onde está localizando seu primeiro exemplo
data:login
type: 'POST

Look at the documentation of Jquery Ajax

  • I understood, so I put it like this: url: 'index.jsp', data: login, type: 'POST', but on the question of the database answer, how do I({})

  • at query return, you can use that to send the JSON object, if(rs.next()) { send object here}

  • Thanks for responding, so... I don’t know how I do to send, could give me a few tips, as I could do to send?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.