I wrote a program where a user inputs username and password which gets stored into the database.But first ResultSet query checks if the username input is already available in the database and then runs the codeblock in the 'if' statement and doesnt add the username input. Else it does. But in this program whenever user is inputting data , it is inserted into the browser even if the user input matches the username query in the database
Form:
<body>
<form name="loginForm" method="post" action="log.jsp">
Username:<input type="text" name="user" />
<br/>
PassWord:<input type="password" name="pass">
<br/>
<input type="submit" value="Sign Up!">
</form>
</body>
log.jsp:
<%@ page import= "java.sql.*" %>
<%
String s1=request.getParameter("user");
String s2=request.getParameter("pass");
Connection con=null;
Statement st=null;
ResultSet rs=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","pass");
if (s1.equals("") || s2.equals("")){
out.println("<script>alert('Please Enter valid credentials');</script>");
}
else{
st=con.createStatement();
rs=st.executeQuery("select users from NewUsers");
while(rs.next()){
String s3=rs.getString("users");
if(s1.equals(s3)){
out.println("Username already exists");
}
else{
try{
st.executeUpdate("insert into NewUsers(users,pass) values('"+s1+"','"+s2+"')");
}
catch(SQLException sql){}
finally{
out.println("Signed Up , Go here for login:<a href='login.jsp'>Here</a> ");
}
}
}
}
}
catch(ClassNotFoundException cnfe){}
finally{
if(st!=null)try{st.close();}catch(SQLException ignore){}
if(rs!=null)try{rs.close();}catch(SQLException ignore){}
if(con!=null)try{con.close();}catch(SQLException ignore){}
}
%>
I dont understand why even after not putting anything the input , the else statement is not executing? Is there some default value in the input?
Edit: Figured it out:
ps=con.prepareStatement("select users from NewUsers u where u.users=?");
ps.setString(1,s1);
rs=ps.executeQuery();
if(rs.next()){
out.println("<script>alert('User already exists')</script>");
}else{//dbUpdate}