0

I've a servlet that checks username and password from database.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
        if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
            String username = req.getParameter("usrnm");
            String userpass = req.getParameter("pwd");
            String strQuery = "select * from user where username='" + username + "' and  password='" + userpass + "'";
            System.out.println(strQuery);
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(strQuery);
            if (rs.next()) {
                req.getSession(true).setAttribute("username", rs.getString(2));
                res.sendRedirect("adminHome.jsp");
            } else {
                res.sendRedirect("index.jsp");
            }
        } else {
            res.sendRedirect("login.jsp");
        }
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
ken
  • 145
  • 1
  • 2
  • 6

1 Answers1

4

You need to properly handle exceptions. You should not only print them but really throw them.

Replace

    } catch (Exception e) {
        e.printStackTrace(); // Or System.out.println(e);
    }

by

    } catch (Exception e) {
        throw new ServletException("Login failed", e);
    }

With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.

There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.

See also:


Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • Yeah! Thanks alot Bro. I changed to ` } catch (Exception e) { throw new ServletException("Login failed", e); }` and I got a display of the exception which showed that my database name was non-existent. I had mvs_user for database yet the real name is mvs_users. Good to have programming brains like yours. Cheers! – ken May 18 '11 at 14:31