Submitting form to Servlet which interacts with database results in blank page

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.


Solution 1:

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:

  • How should I connect to JDBC database / datasource in a servlet based application?
  • How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
  • The infamous java.sql.SQLException: No suitable driver found

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.