How to change if-else to switch in jsp? - java

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.

Related

Getting information from database to be displayed on projects

Im trying to get information in sql from database, there are two entries in each column but and with the following code, i am able to get the first entry information, if i wanted to get the second entry's records and display it also in project how would i get it?
String username1= rs.getString ("USERNAME");
String password1= rs.getString ("PASSWORD");
String aname1= rs.getString ("a_name");
String aname2= rs.getString ("a_name");
System.out.print("Enter Your Username: ");
String usernamea=(br.readLine());
System.out.print("Enter Your Password: ");
String passworda=(br.readLine());
if ((usernamea.equals(username1) && (passworda.equals(password1))))
{
System.out.println("Login Success! Welcome "+aname1+"!");
System.out.println("You are granted with Admin Acess!");
rs.close();
}
else if ((usernamea.equals(username2) && (passworda.equals(password2))))
{
System.out.println("Login Success! Welcome Guest User!");
rs.close();
}
I'm not quite sure what you are asking, nor am I sure how the code you posted actually relates to what you are asking.
When you say "you want the 2nd entry", I am assuming you mean the 2nd record in the SQL table.
try(Connection conn = DriverManager.getConnection(url, username, password)){
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
rs.next();
//All data stored in the ResultSet obj, to which you may loop through & select rows of interest. Particularly useful methods are .getMetaData(), .getRow(), etc.
}
Hopefully this is what you are asking for.
If you already have a ResultSet rs, you can call rs.next(). For Example some Code:
if (rs.next())
{
s.name = rs.getString(1);
s.creator = rs.getString(2);
s.dbname = rs.getString(3);
s.tsname = rs.getString(4);
s.cardf = rs.getFloat(5);
s.npages = rs.getInt(6);
s.statstime = rs.getString(7);
s.avgrowlen = rs.getInt(8);
}
Considering your code:
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
String username1 = rs.getString ("USERNAME");
String password1 = rs.getString ("PASSWORD");
String aname1 = rs.getString ("a_name");
rs.next();
String username2 = rs.getString ("USERNAME");
String password2 = rs.getString ("PASSWORD");
String aname2 = rs.getString ("a_name");
Now you can check both the first entry and the second.
Nevertheless, the better practice is to create a user object, save username, password and aname in it.
Then, using some loop, you can go through the entire result set and get all the information from it.
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
List<User> userList = new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUsername(rs.getString ("USERNAME"));
user.setPassword(rs.getString ("PASSWORD"));
user.setAname(rs.getString ("a_name"));
userList.add(user);
}

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