Suggested articles for you:

59 thoughts on “Session and Role based Java Login example

  1. 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
  2. swap

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

    Reply
  3. shehantha edirisinghe

    how to enter the role in database in this code.

    Reply
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
      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
  11. hanane

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

    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
  12. 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
  13. 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
  14. 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..

This site uses Akismet to reduce spam. Learn how your comment data is processed.