Displaying a users first name on Welcome page through a servlet JDBC - java

I have the working code here to pull all info that I need from my users and user info table located in an oracle database :
try
{
conn = DB_Admin.getConnection();
pstmnt = conn.prepareStatement("SELECT u.username, u.password, ui.user_id, " +
"ui.f_name, ui.l_name, ui.email, ui.dob FROM users u " +
"JOIN user_info ui ON ui.user_id = u.user_id " +
"WHERE u.username = ? AND u.password = ?");
pstmnt.setString(1, username);
pstmnt.setString(2, password);
rs = pstmnt.executeQuery();
boolean exists = rs.next();
...
And I have a servlet which is I am trying to make display the users first name after he/she logs in:
String username = request.getParameter("username").toString();
String password = request.getParameter("password").toString();
User user1 = new User(username, password);
User user2 = new User(username,password, user1.getF_name(), user1.getL_name(), user1.getEmail(), user1.getDob());
//HttpSession session = request.getSession();
//session.setAttribute("f_name", user1.getF_name());
boolean valid = ud.login(username, password);
try{
if(!valid)
{
// request.setAttribute("var", companies);
response.sendRedirect("login.html");
logger.warn("Login Servlet : " + username + " has failed at logging in");
}
else
{
//response.sendRedirect("index.jsp");
request.setAttribute("f_name",user2.getF_name());
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
logger.info("Login Servlet : " + username + " has logged in");
}
}
catch (Exception ex) { out.println(ex.getMessage()); }
In my User class I have getters and setters for all fields: "f_name, email, etc."
I know this code is written incorrectly, and I keep getting a "null" value on my welcome page.

First you should be able to get data you need from the executed query this way
String username = null;
while(rs.next){
username = rs.getString(1);
}
rs.getString method can be called either by index of columns in the order you have made in the executing query OR you can simple place the number by the name of the column of the original database
for example:
username = rs.getString("username");
Here you have the username returned in the executed query and you can easily print it in the jsp

Related

How to change if-else to switch in jsp?

I am new in java there is a piece of code which is written in if-else i want to change this to switch statement but i have no idea to write in switch statement.Here is my code.
<%
String userid = request.getParameter("username");
String pwd = request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/auto_lube","root", "password");
Statement st = con.createStatement();
ResultSet rs; `rs = st.executeQuery("select * from users where uname='" + userid + "' and pass='" + pwd + "' and role='users'");`
if (rs.next()) {
String username = rs.getString("uname");
String email = rs.getString("email");
session.setAttribute("customer_name", username);
int user = rs.getInt("id");
session.setAttribute("customer_id", user);
if(dat.after(date)){
MailClient client = new MailClient();
String from="username#gmail.com";
String to = email;
String subject="Please Attention";
String message="Please change your vehicles oil today is expiery date?";
client.sendMail(from,to,subject,message);}
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("index.jsp");
} else {
response.sendRedirect("invalid.jsp");
}
The real question here is - how can my code divert to the invalid page when the query returns no results.
You should look at this - https://stackoverflow.com/a/6813771/1355930 - which shows a better way of working with result set. Your code should read something like:
if (rs.isBeforefirst()) {
// do the stuff for logged in user
response.sendRedirect("index.jsp");
} else {
response.sendRedirect("invalid.jsp");
}
My guess, though, is that the problem isn't your if statement. Try redirecting to the invalid.jsp in all cases to make sure that you can actually do that redirect.

Duplicate entry whilst using Insert in preparedStatment and retrieving previous data whilst matching results

public int addUsers(int USER_ID,String FIRST_NAME,String LAST_NAME,String PASSWORD,String USERNAME,String USER_PERMISSION) throws SQLException {
Connection conn = null;
conn = getConnectivity(conn) ;
getConnectivity(conn);
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equals(USERNAME)){
System.out.println("Username already exists");
conn.close();
}
else{
System.out.println("FOUND ELSE");
String sql = "INSERT INTO USER_DETAILS VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, USER_ID);
ps.setString(2, FIRST_NAME);
ps.setString(3,LAST_NAME);
ps.setString(4,PASSWORD);
ps.setString(5,USERNAME);
ps.setString(6,USER_PERMISSION);
int result = ps.executeUpdate();
System.out.println(result);
}
}
conn.close();
return USER_ID;
}
and for login I am using
public boolean login(String USERNAME, String PASSWORD) throws SQLException
{
boolean result = false;
Connection conn = null;
conn = getConnectivity(conn) ;
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
String Password = rs1.getString(4);
String UserPermission = rs1.getString(6);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equalsIgnoreCase(USERNAME) && Password.equalsIgnoreCase(PASSWORD) && UserPermission.equalsIgnoreCase("blocked")){
System.out.println("User Logged in");
conn.close();
}
System.out.println("gets out of the code");
}
conn.close();
return result;
}
first of all it is allowing to enter more than one entry, so duplicates occurring regardless of my if statement, and when i add fresh new data and try to see I can log in, it still compares with previously added data and does not work. Can someone see what am i doing wrong here. please thanks
below is the system print out i get ,
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macbook (these i have already in my database)
password input hello (these i have already in my database)
gets out of the code
Connection Valid
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macho (these i have already in my database)
password input hello (these i have already in my database)
FOUND ELSE (dont know why it adds data when they already exist in database)
1
Your code doesn't make sense: you are querying for all users and only checking the first returned user if it matches. Of course that is going to fail if the first returned user doesn't match: in addUsers you will try to add the user if the first user returned doesn't match, in login a user can only login if it is the first user.
You need to use a WHERE clause to only request the user you want to check:
// Note: this assumes a case insensitive collation
String sqlSelect = "SELECT * from USER_DETAILS WHERE username = ?";
try (PreparedStatement pres = conn.prepareStatement(sqlSelect)) {
pres.setString(1, USERNAME);
try (ResultSet rs1 = pres.executeQuery()) {
if (!rs1.next) {
// user doesn't exist yet, create...
}
}
}
You need to do something similar for login (but then with if (rs1.next()) instead).
There are more problems with your current code: you are storing plaintext passwords: you should really hash them with a strong password hash like PBKDF2. Also please follow the java naming conventions. Variables and parameters are camelcase so not USERNAME but username (or userName), not UserPermission, but userPermission. This improves the readability for people who are used to the java naming conventions.

Login page is not working in JSp when i put Empty User name and password

<%# page import="java.sql.*"%>
<%
String userid = request.getParameter("uname");
String pwd = request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from members where uname='" + userid
+ "' and pass='" + pwd + "'");
if (rs.next()) {
session.setAttribute("userid", userid);
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("index.jsp");
}
else {
out.println("Invalid password <a href='FirstPage.jsp'>try again</a>");
}
%>
This is my code for a Login page.
I am validating from the database and checking if a user exists.
If the user exists, login succeeds, if not, an error message is shown to the user.
When I try to login with an empty user name and password, it also allows to login.
Please check my code and tell me what I am doing wrong.
You can check for the empty String before doing your validation like :
if(userid == null || pwd == null) {
request.sendRedirect("home.jsp"); // return; // do what ever you want to exit. }
}

setting variables against data retrieved from a database

I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}

formatting a prepared statement to inquire a database

I am working on a project to create a login page. To do this I am using a database to store the user information. As of right now there are four columns in my database: username, password, email, and admin.
Right now I am having a problem accessing that database using a prepared statement/Result set format. Right now I get to the third return, print out the imputed username and password then generate an error. Am I formatting my prepared statement incorrectly?
Okay, based of previous answers I have corrected most of my code(thank you) and now I have this error when I am trying to print out of the result set:
java.sql.SQLException: Column Index out of range, 2 > 1.
any ideas?
My code:
Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "root");
props.setProperty("databaseName", "dbname");
String ret = ERROR;
Connection myCon = null;
try{
System.out.println("got here 1!");
Class.forName ("com.mysql.jdbc.Driver").newInstance();
System.out.println("got here 2!");
myCon = DriverManager.getConnection("jdbc:mysql://ipaddresshere:3306/dbname",props);
System.out.println("got here 3!");
System.out.println(username);
System.out.println(password);
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
//PreparedStatement prep = myCon.prepareStatement(dbQuery);"
PreparedStatement ps = myCon.prepareStatement(dbQuery);
ps.setString(1, username);
ps.setString(2, password);
ResultSet result = ps.executeQuery();
System.out.println("got here 4!");
while (result.next()) {
System.out.println("got here 5!");
ret = SUCCESS;
System.out.println("username: "+result.getString(1)+" password: "+result.getString(2)+" email: "+result.getString(3));
if(result.getString(4).toLowerCase()=="YES"){
ret = "admin";
}
}
}catch(Exception e){
System.out.println("arg there be an error me matey!");
ret = ERROR;
}finally{
if(myCon!=null){
try{
myCon.close();
}catch (Exception e){
}
}
}
return ret;
There are multiple problems with your code:
First, you're missing quotes around username and password.
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = '"+username+"' AND password = '"+password+"'";
Second, the PreparedStatement#setString() methods have no effect unless you define your query with place holders ? like
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = ? AND password = ?";
Third, you must never compare strings with equality == operator. Use String.equals() as
// also note you need toUpperCase() here
"YES".equals(result.getString(4).toUpperCase());
Change the line:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
By:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = ? AND password = ?";

Categories

Resources