Issue
im pretty new in java and making a program that functions with jsp, servlets and a postgresql database. There are three pages the user can access after the login, all depending on the status that has been saved in the database. The problem is that the status of the user (admin
,seller
,client
) isn't retrieved from the check_user
class to the login.
The login servlet
@WebServlet(name = "login")
public class login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String loginuser = request.getParameter("loginuser");
String loginpassword = request.getParameter("loginpass");
String status = " ";
check_user user = new check_user();
try {
users usercheck = user.check_user(loginuser, loginpassword,status);
status = usercheck.getStatus();
String dest_page = "index.jsp";
if (usercheck != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
session.setAttribute("status", status);
if (status =="Client") {
dest_page = "/client_page.jsp";
}
else if(status =="Seller"){
dest_page = "seller_page.jsp";
}
else{
dest_page = "admin_page.jsp";
}
}
else {
String message = "invalid username or password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(dest_page);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
The check_user
class
public class check_user {
public users check_user(String username, String password,String status) throws SQLException, ClassNotFoundException {
String jdbc_url = "jdbc:postgresql://localhost:5432/database";
String dbUser = "postgres";
String dbPassword = "pass";
Connection connection = DriverManager.getConnection(jdbc_url, dbUser, dbPassword);
String sql = "SELECT * FROM database.public.users WHERE username = ? and password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
users user = null;
if (result.next()) {
user = new users();
user.setUsername(result.getString("username"));
user.setPassword(password);
user.setStatus(result.getString("status"));
}
connection.close();
return user;
}
}
I am confident the issue is that the status isn't retrieved from the check_user
because running the login without the if statements deciding on the page runs normally and returns to any jsp page i select.
I have been racking my brain for two days now and i can't figure it out.
Solution
One issue with the code which is quite evident in that the string comparison is not correct.
Instead of using - if (status =="Client") Use if (status.equalsIgnoreCase("Client"))
Answered By - Reshmi Nair
Answer Checked By - Katrina (JavaFixing Volunteer)