Suggested articles for you:

107 thoughts on “What is a Session? How to Develop a Role based Login Application in Java?

  1. Woye Ahmed

    Great Tutorial. so helpful indeed. but if i want my users to have access to different url pages how would i go by this

    Reply
    1. Ravi Bandakkanavar Post author

      Thanks Ahmed.

      I am not clear about your question. Do you want to give access to different pages in your application to logged in users? If yes, you just have to include session variable everywhere.

      Reply
  2. Abdulla

    Sir I get this error when run on tomcat 8.5 “The origin server did not find a current representation for the target resource or is not willing to disclose that one exists”

    Reply
  3. querydevelopers

    hey,
    m getting an error 404 not found
    what could the problem be after following everything according to your code

    Reply
  4. Shubham Jadhav

    I get one error >>>> Unknown column ‘roll’ in ‘field list’.
    Same code i have written.

    Reply
    1. Shubham Jadhav

      Sir, code runs successfully…..Sorry for asking the easier query.

      Reply
    1. Ravi Bandakkanavar Post author

      Hi Nourhen,
      Many things need to be modified in order to implement hibernate. I would suggest you to go through hibernate examples first.

      Reply
  5. Ishika

    Hi Ravi, I want to use this code with Postgres SQL. can you please tell me what changes should i need to do. I Update DBConnection file with postgres configuration and also updated postgres jar file. But i am getting error Invalid Credential while running this code. Please help

    Reply
  6. Ishika

    Hi Ravi, I followed your code but not to able to login. Everytime it’s giving me an error Invalid User Credentials!! Please help

    Reply
  7. Ishika

    Post establishing a DB connection – org.postgresql.jdbc3g.Jdbc3gConnection@92bfa68
    Error message = Invalid user credentials

    Reply
      1. Ishika

        User details exist in database. I also tried to print user details and its fetch user details from database successfully. But it not redirecting user according to his role. Instead it giving error only. And this case happening with PostgreSQL only. With using MySQL database same logic working very well.

        Reply
      2. Ishika

        Hey is runing successfully. Actually there was space in my db data. now problem solved :-)
        I need to do it with hibernate. Can you suggest me what changes should i need to do? Thanks

        Reply
        1. Ravi Bandakkanavar Post author

          Good to know that this is working for you.
          Many things need to be changed if you want to implement hibernate for this example. I would suggest you to go through hibernate examples first.

  8. Ishika

    Hi..I follow this tutorial and facing an issue. I entered username and password in login form but it doesn’t allow me to access admin/user page instead it continuously shows Invalid user credentials. Please help!!!

    Reply
  9. danish

    hey you can not understand my question ..
    Look user role is login with session after user go user.jsp page , But user click the back than show login page.
    Which condion apply on “login.jsp” page the session login user not back login.jsp page
    logout compulsary

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Danish,

      If you don’t want to go back after successful login, you can use the javascript code to disable the browser back button.

      Reply
  10. danish

    My question is User login not access admin page which condition i apply

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Danish,

      If I get your question right, to prevent anyone else accessing the User page, the following code will do the job.

      < % //In case, if User session is not set, redirect to Login page. if((request.getSession(false).getAttribute("User")== null) ) { %>

      Reply
      1. Saral

        sir, i have got error in the code so i send all mine code can you please check it out

        Reply
  11. Soulia

    Thank you, what if i want to use sql server instead of mysql?

    Reply
    1. Ravi Bandakkanavar Post author

      Its simple. Just modify DBConnection.java.
      The following 2 lines.

      url = “jdbc:mysql://localhost:3306/customers”;
      Class.forName(“com.mysql.jdbc.Driver”);

      Reply
  12. grt

    Hello, I’m using your code, thank you!

    But I would like to ask how to replace the “Invalid credentials” to an alert message or popup message. So when the user entered wrong data, the popup message will come up instead of adding “invalid credentials” to the form.

    Reply
    1. grt

      Also when I try to run it, once i pass the loginservlet, it doesn’t load the CSS, Images, and other href links when I’m in welcome page already. What should I do?

      Reply
  13. SURYANARAYAN RATH

    Why you used session.setAttribute()?what is the use of setting the session id when not used..

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Surya,

      Good question. Yes. We must use it. It was missed in the code. I have added it in each JSP. You can recompile your code and verify this.

      < % //In case, if Admin session is not set, redirect to Login page if((request.getSession(false).getAttribute("Admin")== null) ) { %>

      < %} %>

      Reply
  14. Ian

    What if i go directly to this link example/user or example/user/user.jsp, how will I know if a session is ongoing and/or the role is correct? thank you and kudos

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Ian,

      Sorry. The session validation was missed in the code. We must validate if the session is set for each user role. The condition must be added for each user role. You can recompile your code and verify if you still see this issue. Thanks for the catch and comment

      if((request.getSession(false).getAttribute(“Admin”)== null) )

      Reply
    1. Ravi Bandakkanavar Post author

      Hi Andy,

      Good catch. The session validation was missed in the code. We must validate if the session is set for each user role. I have added the condition in 3 JSPs. You can recompile your code and verify if you still see this issue.

      < % //In case, if Admin session is not set, redirect to Login page if((request.getSession(false).getAttribute("Admin")== null) ) { %>

      < %} %>

      Reply
  15. Hitech ICT South Africa

    Hi
    I receive the error below after deployment with embedded Eclipse Tomcat v7, plz help

    SEVERE: Allocate exception for servlet LoginServlet
    java.lang.ClassNotFoundException: za.co.sapo.servlet.LoginServlet
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)

    Reply
      1. Manishankar

        I am getting Http 404 status error while running project
        But i am getting jsp pages while i am running individually

        Reply
        1. Ravi Bandakkanavar Post author

          Hi,

          Did you create a dynamic web project? Did you refer to each step given in the video?
          The 404 error occurs when the page/file you are accesing doesn’t present with the same name.

  16. nealac23

    Hi, I created a project using both the registration and this login. Being that the respective web.xml files are different how can I make them coexist?

    Reply
      1. nealac23

        So I have to copy and paste the web.xml related to ‘login’ under the web.xml of ‘registration’?

        Reply
    1. Ravi Bandakkanavar Post author

      Yes. Of course they can coexist. Web.xml will be common file containing all the servlet information in this case. I’m soon going to post an example containing both login and servlet.

      Reply
  17. fl4y3r5

    how can i put 2 or more people into the same jsp ?

    Reply
  18. swap

    after mentioned time it should show invalid page if refreshed its not happening a i refresh browser it shows data after login

    Reply
    1. Ravi Bandakkanavar Post author

      For which used did you check it?

      The following value sets the session duration of 10 minutes for all the roles.
      10

      Reply
  19. shehantha edirisinghe

    how to enter the role in database in this code.

    Reply
  20. oussma

    how can i after loging in show the name and all informations in the jsp while my table compte has only username and password

    Reply
    1. Ravi Bandakkanavar Post author

      Once you log in, you will have only username and password with you.

      You can do two things.
      1. Get corresponding user’s information from another table ( say customer details).
      2. Add extra columns in the same table and fetch the details.

      Reply
  21. Malathi

    Hello Ravi,

    Can i get the similar concept with Spring Boot & Hibernate, JPA. I am getting confused in where to start, could you pls help me to create role based login using spring boot..I am using Gradle as build tool, IDE:STS, spring boot version:1.5.10.. Pls help me out to achieve role based functionality in spring without spring security,but using sessions..Thanks in advance!

    Reply
  22. adil

    i use only user role. that’s it. Not multiple role use.

    this code use in “login.jsp” page.

    it’s not work.

    Reply
  23. Adil

    Session login user successful login and redirect to user.jsp page but I click back button that show login.jsp page.

    My question is session user login successfully login the user click on back button they do not back to login.jsp
    compulsary click on logout link after user logout .

    I use this code in login.jsp page but not work

    If (session.getAttribute (“Student”)!=null)
    {
    response.sendRedirect (“login.jsp “);
    }

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Adil,

      Let me help you.
      Your question is, initially when you log in, it will take you to the user.jsp. You want to click on the back button and then go to the Student.jsp page. Is it correct?

      The role based login is decided based on individual roles. If you want to act both as a student and user, you would need to handle the session for both the roles/users.

      Reply
  24. adil

    hey i use your code my question is session login user not back to login.jsp.?
    it means session login user not back to login.jsp page
    which condition i apply ?

    Reply
  25. adil

    hey my question is session login user not back to login.jsp page.
    mean session login user not back to login.jsp page not direct type to url.
    which condition i apply.

    i use your code.

    Reply
  26. Adil

    My questions is I login success , but do not back to login.jsp page
    Means login session user not back to login.jsp page which condition use.

    Reply
  27. Ghosh

    I am getting java.lang.NullPointerException error
    HELP ME!!!!!

    Reply
      1. Ghosh

        Hey dude it is working :).
        You should have use switch case and break in LogIN.java Servlet
        ” DaoImpl dao=new DaoImpl();
        try
        {
        String userValidate = dao.authenticUser(usr);
        switch (userValidate) {
        case “Employee_Role”:
        {
        System.out.println(“Employee”);
        HttpSession session = request.getSession(); //Creating a session
        session.setAttribute(“Employee”, email); //setting session attribute
        request.setAttribute(“email”, email);
        RequestDispatcher rd=request.getRequestDispatcher(“./Employee.jsp”);
        rd.forward(request,response);
        break;
        }
        case “User_Role”:
        {
        System.out.println(“User”);
        HttpSession session = request.getSession(); //Creating a session
        session.setAttribute(“User”, email); //setting session attribute
        request.setAttribute(“email”, email);
        RequestDispatcher rd=request.getRequestDispatcher(“./User.jsp”);
        rd.forward(request,response);
        break;
        }
        default:
        {
        System.out.println(“Error message = “+userValidate);
        request.setAttribute(“errMessage”, userValidate);
        RequestDispatcher rd=request.getRequestDispatcher(“./Login.jsp”);
        rd.forward(request, response);
        break;
        }
        }
        }


        If else also works but it is better to use switch case and break.

        Reply
      2. Ghosh

        In before it wasn’t working in login.
        When I click Login button it shows null pointer exception but now it’s gone.
        I did remove lot of mistake in the code.

        Reply
  28. hanane

    great work. i was wondering are you trying to get an access to an xml file? thanks

    Reply
    1. Ravi Bandakkanavar Post author

      Thank you Hanane.

      Answer – Nope. It gets generated for servlets and you need to modify it as per the servlet path and your requirements.

      Reply
      1. hanane

        Thank you Ravi for your answer. So can i change it to read xml file using rbca? if so can you tell me where i could make changes. it would be really nice.

        Reply
  29. Ferry

    Ravi I tried using your code but it always give me an error : Error message = Invalid user credentials .Although I am using the correct credentials for the login process.

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Ferry,

      This is strange.
      Did you verify the user details in your database? Make sure your role is also matching along with the user details.

      One of the following conditions must be satisfied in order to log-in successfully.
      if(userName.equals(userNameDB) && password.equals(passwordDB) && roleDB.equals("Admin"))
      return "Admin_Role";
      else if(userName.equals(userNameDB) && password.equals(passwordDB) && roleDB.equals("Editor"))
      return "Editor_Role";
      else if(userName.equals(userNameDB) && password.equals(passwordDB) && roleDB.equals("User"))
      return "User_Role";

      You can also go through the video https://youtu.be/swdx5g0X1hk to understand the flow.

      Reply
        1. Ravi Bandakkanavar Post author

          Hi Ferry,

          That’s great.
          Could you please let others know what was the issue and how were you able to resolve it?

  30. Martijn

    Hi Ravi – I followed your tutorial on youtube “Session and Role based Java Login example”. Very helpful and everything is working fine. But for my school exercise I want to change the 3 roles and add 3 additional roles. But as soon as I change e.g. Admin to a different name (in all code and classes) it keeps on saying invalid user. Any tips on how I can change the roles and add additional ones? Thanks in advance!

    Reply
    1. rahul

      connected with database but olways show err message with user name. how is this possiible

      Reply
      1. rahul

        Error message = abhi
        abhi
        Post establishing a DB connection – com.mysql.jdbc.JDBC4Connection@6541f4
        Error – abhi
        Error message = abhi

        this type of error occur everytime….
        help me

        Reply
      1. nofar

        how can i catch the username from session in HTML file?

        Reply
  31. Shanmukh Madhavarapu

    I have followed every step of it, but I am getting following error.

    The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

    Path in URL is:http://localhost:8080/Sample/LoginServlet

    Can you tell me what is the problem?

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Shanmukh,

      Looks like you are maintaining different directory structure. Did you modify the web.xml and action=”” attribute in the Login.jsp accordingly?

      Also, look for the welcome-file in the web.xml.

      If you use my code as it is, you should be able to access login form with the URL – http://localhost:8080/LoginRoleSession/

      You can also refer to the video for a clear understanding – https://www.youtube.com/watch?v=swdx5g0X1hk

      Let me know if this does not solve your problem.

      Reply
        1. Ravi Bandakkanavar Post author

          I want to know if your LoginServlet is being called or is it failing while routing requests to LoginServlet.

          Please add sysout statements in LoginServlet. You can try displaying username input in the beginning of the servlet.

          Have you kept web.xml under WEB-INF folder?
          Are you using request.getContextPath()? Try removing it.

          What tomcat version are you using?

        2. Shanmukh Madhavarapu

          I am getting error in initiating the servlet. I am uisng tomcat9 server

        3. Ravi Bandakkanavar Post author

          Yes. It is not able to locate your servlet. In the action just specify LoginServlet as shown in the link http://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern

          1.Hope you are using doPost method and your code look like following
          public class LoginServlet extends HttpServlet {

          public LoginServlet() {
          }

          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

          2. Also, try loading servlet-api.jar in the execution path.

          3.you can simply start with a new project by copying code for login and servlet only two files.

Did it help? Comment here..