0

i implemented simple servlet that checks if the user exists in the DB, and if so he can continue to main site.

The servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //obtain CustomerDB data source from Tomcat's context
            Context context = new InitialContext();
            BasicDataSource ds = (BasicDataSource)context.lookup(testAppConstants.DB_DATASOURCE);
            Connection conn = ds.getConnection();

            //Checks if the username and password exists in the DB
            PreparedStatement ps = conn.prepareStatement(testAppConstants.SELECT_USERS_BY_NAME_STMT);
            ps.setString(1,request.getParameter("username"));
            ResultSet rs  = ps.executeQuery();

            Boolean isMatch = false;

            if(rs.next())
            {

                String a = request.getParameter("password");
                String b = rs.getString("Password");
                if(a.equals(b))
                {
                    response.sendRedirect("success.html");
                    isMatch = true;
                }
            }

            if(!isMatch)
            {
                response.sendRedirect("index.html");
            }

            //commit update
            conn.commit();
            //close statements
            ps.close();
            //close connection
            conn.close();

        } catch (SQLException | NamingException e) {
            getServletContext().log("Error while closing connection", e);
            response.sendError(500);//internal server error
        }

        return;
    }

i am using response.sendRedirect() function but in success page how can i authenticate the user and determine if he have permission or not. i am not allow to use JSP.

Thanks.

user11001
  • 372
  • 3
  • 14
  • Why not use [JavaEE security](https://docs.oracle.com/javaee/7/tutorial/security-intro001.htm)? Why try and implement homebrew security? – Boris the Spider Feb 02 '16 at 22:32
  • P.S. your resource handling is really very dangerous. Please use [`try-with-resources`](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). – Boris the Spider Feb 02 '16 at 22:34

1 Answers1

-1

If just want to keep it simple.

ps=conn.prepareStatement("Select * from Table where uname='?' AND password='?');
ps.setString(1,"uname");
ps.setString(2,"password");
int i=0;
ResultSet rs=ps.executeQuery();
while(rs.next){
i++;
}
if(i>0){
//record exist i.e. valid
}
else{
//no record i.e. invalid
}

Please handle exceptions

Ars
  • 282
  • 2
  • 9
  • 26