0

Please i have some doubt about my ConnectLogin and my ServletValidLogin: My ConnectLogin

    package br.com.cad.dao;

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

import br.com.cad.basica.Contato;
import br.com.cad.dao.ConnectDb;

public class ConnectLogin extends ConnectDb {

    public Contato getContato( String email, String senha ){

        Connection c = this.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{


            ps = c.prepareStatement("select pf_email, pf_senha from dados_cadastro where pf_email = ? and pf_senha = ?");
            ps.setString(1, email);
            ps.setString(2, senha);

            rs = ps.executeQuery();

            if ( rs.next() ){
                Contato user = new Contato();
                user.setEmail(email);
                user.setSenha(senha);
                user.setNome( rs.getString("pf_nome") );

                return user;
            }
        }
        catch (SQLException e){
            e.printStackTrace();
        }
        finally{
            if (rs != null ) {
                try { rs.close(); } catch (SQLException e) { ; }
                rs = null;
            }
            if (ps != null ) {
                try { ps.close(); } catch (SQLException e) { ; }
                ps = null;
            }
            if (c != null ) {
                try { c.close(); } catch (SQLException e) { ; }
                c = null;
            }
        }
        return null;
    }
}

My Servlet:

package br.com.cad.servlet;

import java.io.IOException;
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 br.com.cad.dao.ConnectLogin;
import br.com.cad.basica.Contato;

public class ServletValidaLogin extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

        HttpSession session = request.getSession(); 
        Contato user = null;
        String email = request.getParameter("email"); 
        String senha = request.getParameter("password"); 

        try {
            ConnectLogin dao = new ConnectLogin(); 
            user = dao.getContato(email, senha);
        }
        catch ( Exception e ){

        }


        if ( user == null ) {
            session.invalidate();
            request.setAttribute("msg", "Usuário ou senha inválidos");
            request.getRequestDispatcher("login.jsp" ).forward(request, response);
        }
        else{

            session.setAttribute("user", user);
            request.getRequestDispatcher("home.jsp" ).forward(request, response);
        }

    }

}

And my ConnectDb:

    package br.com.cad.dao;

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


public class ConnectDb {  

    public Connection getConnection() {  
        try {  
            System.out.println("Connect to database...");  
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/soa", "root", "wey123");  
        } catch(SQLException sqlException) {  
            throw new RuntimeException(sqlException);  
        }  
    }

I don't know what is wrong and why is returned in my console: Connect to database... in my webpage is returned user and password invalids! I think the problem is with my ConnectLogin but what?

Wesley Heron
  • 413
  • 2
  • 12
  • 27

2 Answers2

0

I would look into Spring, and Spring Security, Spring offers good tested system to secure website and manage db connections.

Currently it supports DB-backed, JNDI-backed security or you can just hardcode users and roles. With spring you can secure just sections of the site or methods

Here is more info about security itself http://static.springsource.org/spring-security/site/tutorial.html

PulsAm
  • 71
  • 5
  • I highly doubt OP will look into that since he is having trouble with plain JDBC. Then again, you never know. – Andy Jul 10 '13 at 06:02
0

Your "bug" could be one of two things. It could be that you are not even connecting to the database. In ConnectDb.java you are throwing a RunTimeException but in ServletValidaLogin.java you are swallowing that exception. Add a System.out.println(e.getMessage()) in the catch block to make sure that you are indeed able to connect.

try {
    ConnectLogin dao = new ConnectLogin(); 
    user = dao.getContato(email, senha);
}
catch ( Exception e ){
    System.out.println(e.getMessage()); 
}

What will happen in this case is that since you are not connected, you will go to the catch block, then your if statement in ServletValidaLogin

if ( user == null )  

will evaluate to true and you will see your error message. Side note: You are catching a lot of exceptions without outputting/logging any of them. You should consider adding println statements in all of them. It will make it easier for you to debug.

If you are able to connect, then it could be that your ResultSet is not pointing to anything after you execute the query. If that's the case if ( rs.next() ) will evaluate to falsein ConnectLogin.java and your method will return null instead of a user. It could be that you have a bad query (not sure if you should be getting an error message though, I haven't use plain JDBC in a long time). In any case, access mysql directly and add a fake user and try your query on that dummy user. If you can find him than maybe your issue might be in your insertion (ok, so 3 possible causes).

UPDATE

It seems like your actual problem was that you were referencing the wrong name in your getRequest method for password. We determined that the name for attribute <input>was actually senha and made the necessary changes.

Note: Instead of

user.setEmail(email);
user.setSenha(senha);

It should be

user.setEmail(rs.getString("pf_email"));
user.setSenha(rs.getString("pf_senha"));

(although not completely necessary because of your ifcondition but it makes more sense to set them to what the query returns...at least for me).

Also,

user.setNome( rs.getString("pf_nome") );

should not even be here since it's not in your select statement.

Lastly (unrelated to your main problem), you should seriously consider synchronizing HttpSession. It is not thread safe. You can read the answer below to get started if you want to know why. There are many more articles on the web that talk about this.

Is HttpSession thread safe, are set/get Attribute thread safe operations?

Community
  • 1
  • 1
Andy
  • 5,900
  • 2
  • 20
  • 29
  • I fixed it but dont works continues printed in eclipse console: Connect to database... and in form user and password invalid! – Wesley Heron Jul 10 '13 at 21:14
  • @Wesley Can you tell me what is it that you fixed exactly ? Are you sure you can connect to the db ? – Andy Jul 10 '13 at 21:24
  • @Wesley Try to insert a few users through your program and then bring up mysql console directly (NOT through Java). Access the db and run this query `SELECT * FROM dados_cadastro`. Are you seeing the users you inserted in the db ? – Andy Jul 10 '13 at 21:29
  • Yeah, in my aplication i have a webform to add user in my DB and they are there stored i saw it through Select * from dados_cadastro and in my login form i insert the email stored in db and your pass but i get a user and password invalid and the consolo Connect to database... as in System.out.Println in my Class ConnectDB – Wesley Heron Jul 10 '13 at 21:51
  • Now my Class ConnectLogin is: if ( rs.next() ){ Contato user = new Contato(); user.setEmail(rs.getString("pf_email")); user.setSenha(rs.getString("pf_senha")); user.setNome( rs.getString("pf_nome") ); return user; } – Wesley Heron Jul 10 '13 at 21:54
  • I think that i have a problem when i insert my email and passwaord and press submit button in this time my DB dont get a connection but what i dont understand? – Wesley Heron Jul 10 '13 at 22:05
  • @Wesley What Java version are you using ? Are you also using an IDE ? – Andy Jul 10 '13 at 22:08
  • @Wesley. Just to be sure. You are able to confirm that you are not able to connect to the db when you try to insert correct ? Are you also able to connect when you try to retrieve anything from the db also ? Did you add the `println` statement like I told you in the catch block ? Are you seeing an output ? I just want to make sure. – Andy Jul 10 '13 at 22:12
  • My IDE is eclipse, I am not able to connect to db when i trying to retrieve data from db...I added the println in catch block but nothing is printed just a message Connect to database... in my console – Wesley Heron Jul 10 '13 at 22:32
  • @Wesley That does not sound right. Are you sure you're not able to connect ? You should get a `NullPointerException` at some point no or an Exception at least. Let's assume you didn't get an exception and you didn't connect `connection` should be `null` and when you do `c.prepareStatement` you will get a `NullPointerException` thrown at you. The only way to be 100% sure if to open the mysql terminal directly after inserting some values. – Andy Jul 10 '13 at 22:47
  • @Wesley When you open the terminal make sure also that your query is correct `select pf_email, pf_senha from dados_cadastro where pf_email = 'something' and pf_senha = 'something'` – Andy Jul 10 '13 at 22:53
  • But i insert some values in my mysql throught my Other class that also uses my ConnectDb and i dont get any Exeption or any error. I can not understand where is the error is correct it: public class ConnectLogin extends ConnectDb {... extends is correct? – Wesley Heron Jul 10 '13 at 22:53
  • @Wesley Let's eliminate some possibilities. Please do the following: Insert some values in the database through your webapp. Then, open the mysql terminal and do `SELECT *` and let me know if it's returning anything ? Do you know how to access the terminal ? – Andy Jul 10 '13 at 22:57
  • I know that we can fix it lol... i executed the query in my db and is correct select pf_email, pf_senha from dados_cadastro where pf_email = 'something' and pf_senha = 'something' the data is stored is retrieved. – Wesley Heron Jul 10 '13 at 23:01
  • @Wesley Ok, and this data that you retireved. It was stored through your webapp ? I'm trying to make sure it's not a connection issue. – Andy Jul 10 '13 at 23:03
  • Yeah, i know how to acess the terminal and i just insert some values via terminal and via webform made to create a account. And my data is in my mysql db. I retrieve some values by select * from or select pf_email ... – Wesley Heron Jul 10 '13 at 23:06
  • @Wesley Ok good lol. Should have said that sooner sheesh. Let me think one moment. – Andy Jul 10 '13 at 23:08
  • @Wesley Do me a favor and add a `println` under `String email = request.getParameter("email")` and `String senha = request.getParameter("password");` Are you getting the same values you entered via the form – Andy Jul 10 '13 at 23:10
  • Just println? as 'code'String email = request.getParameter("email");println'code' i dont understand it – Wesley Heron Jul 10 '13 at 23:14
  • @Wesley Yep, add `System.out.println(email)` and `System.out.println(senha)` under those lines. Then try to log in via webapp and let me know if you are seeing the same values you put in. – Andy Jul 10 '13 at 23:16
  • i add so:String email = request.getParameter("email"); System.out.println(email); String senha = request.getParameter("password"); System.out.println(senha); – Wesley Heron Jul 10 '13 at 23:18
  • @Wesley Ok, run your program and let me know what you're seeing ? If you did not see anything you either have the wrong value for `name` attribute of `input` in `getParameter` or you didn't include one at all. – Andy Jul 10 '13 at 23:20
  • hum, i got Connect to database... wesleyfarias@fiema.org.br null (here should be 123) – Wesley Heron Jul 10 '13 at 23:21
  • My password(Senha) is got null – Wesley Heron Jul 10 '13 at 23:21
  • @Wesley Here you go ! I'm betting the name of your `input` was `senha` and not `password` right ? – Andy Jul 10 '13 at 23:22
  • @Wesley In other words your input in the HTML for password should be defined as below ``. You either forgot to add the `name` attribute or the `name` has a different value right ? – Andy Jul 10 '13 at 23:24
  • i think that works but i received this error: HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application – Wesley Heron Jul 10 '13 at 23:26
  • @Wesley If the input name is senha then change this `request.getParameter("password");` to `request.getParameter("senha");` – Andy Jul 10 '13 at 23:26
  • @Wesley Are you using Maven ? Try to do a clean and build – Andy Jul 10 '13 at 23:27
  • whats mean it?org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:56) org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:445) ... – Wesley Heron Jul 10 '13 at 23:27
  • Are you using Maven ? Try to do a clean and build - i dont use MAVEN – Wesley Heron Jul 10 '13 at 23:29
  • @Wesley Try to relaunch the application. – Andy Jul 10 '13 at 23:29
  • @Wesley http://stackoverflow.com/questions/8701307/the-absolute-uri-http-java-sun-com-jsp-jstl-core-cannot-be-resolved-in-either – Andy Jul 10 '13 at 23:30
  • @Wesley It only took us 31 comments lol but we were able to solve it. Good luck with everything. – Andy Jul 10 '13 at 23:35
  • Thanks for help me you are great programmer now i have a other problem HTTP Status 500 - The absolute uri: java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.jav‌​a:56) org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:445) that i look a solution...Thanks!! – Wesley Heron Jul 10 '13 at 23:37
  • @Wesley Lol, I'm not. I ran into your problem a lot. Can you post a new discussion thread ? We're not really suppose to put so many comments and I don't want to get in trouble. Once you ask the question, leave me a comment with the link and I'll look at it. – Andy Jul 10 '13 at 23:40