103 thoughts on “Login application in Java using MVC and MySQL

  1. ranjana

    if I want to access the results of the select query in LoginDao.java lets say the userName password and Role from the user table in LoginServlet.java. In the below code I need to check for the role which I got from the database query how do I do that?
    if(userValidate.equals(“SUCCESS”)) //If function returns success string then user will be rooted to Home page
    {
    request.setAttribute(“userName”, userName); //with setAttribute() you can define a “key” and value pair so that you can get it in future using getAttribute(“key”)
    request.getRequestDispatcher(“/Home.jsp”).forward(request, response);//RequestDispatcher is used to send the control to the invoked page.
    }

    How to do that could you please explain me via code?

    Thanks,

    Reply
    1. Ravi Bandakkanavar Post author

      Ranjana,

      Use following code to fetch the database records and use them in the code.

      while(resultSet.next()) // Until next row is present otherwise it return false
      {
      userNameDB = resultSet.getString(“userName”); //fetch the values present in database
      passwordDB = resultSet.getString(“password”);
      role = resultSet.getString(“role”);

      if(role.equals(“Admin”))
      {
      request.setAttribute(“role”, role); //
      request.getRequestDispatcher(“/Admin.jsp”).forward(request, response);//
      }

      Reply
      1. ranjana

        I am able to fetch the role in LoginDao.java but how to access that role in LoginServlet.

        As LoginDao contains the below code:
        while(resultSet.next()) // Until next row is present otherwise it return false
        {
        userNameDB = resultSet.getString(“userName”); //fetch the values present in database
        passwordDB = resultSet.getString(“password”);
        role = resultSet.getString(“role”);

        and the next part we have to write in LoginServlet as below:

        if(role.equals(“Admin”))
        {
        request.setAttribute(“role”, role); //
        request.getRequestDispatcher(“/Admin.jsp”).forward(request, response);//
        }

        how will we get the value of the role in LoginServlet? Also there is not request object in LoginDao so inthat case we will not be able to set the role in the request object.

        Reply
        1. Ravi Bandakkanavar Post author

          Hi Ranjana,

          Please go through following lines which I have mentioned at the end of the post.

          To check for role you have to assign a role to each user at the time of registration or else admin can assign roles later. The “USERS” table should contain the role.
          The LoginDao.java should return the role to LoginServlet.java and it should be compared and decided on LoginServlet.java page.

          You can achieve this easily by calling another method from LoginServlet to decide on the role. Just fetch role from LoginDao and return it to the LoginServlet.

          Let me know if you have anymore doubts.

          Reply
    1. Ravi Bandakkanavar Post author

      Hi Mahadev,

      Whole code is not with me right now. You can find the logic written at the end of the post.

      Somebody had asked here how to create different roles like Admin, Teacher, Student etc. and redirect them to different pages on login.
      This has to be handled in the LoginServlet.java class

      Reply
  2. Anil Kumar

    Can we write JSP MVC web application without using Java beans.
    Can u explain me why we use Java beans in JSP MVC?*

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Anil,

      You can avoid java bean here. It is not mandatory.
      Beans are mainly used to assign values to all the variables of a class so that they can be accessed easily through the object of the class.
      For example, here we are using only username and password. Since these are fewer details, we can easily assign values to these parameters.

      To avoid bean class here,

      You can directly pass username and password details while calling authenticateUser method.

      String userValidate = loginDao.authenticateUser(userName, passWord)

      Reply
  3. anil

    actually im trying contact app using mvc but i’m getting error in model(model.java) how to rectify this i am not knowing can u help me about this? plz

    there is no time, i have to submit this in 2days

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Anil,

      If you explain more about your error or exact error message, I can help you.
      For any app you can use the same code and modify your logic based on requirements.

      Reply
        1. Ravi Bandakkanavar Post author

          [email protected]

          Reply
            1. Ravi Bandakkanavar Post author

              I have not received anything Anil.
              Could you tell me what is the issue. I cannot go through each and every line of you code.
              In which step you are facing an issue

              Reply
          1. anil

            actually there is no error
            but it is not procedng to further steps like if we are adding contacts in addcontact after submit it want to add in database but it is simply getting a plane window

            Reply
          2. anil

            plz send me a empty mail so I can attach those files to you back by replying

            I tried to send but it is getting like I’m unable to send any mail with attachments I’m waiting for your mail

            Reply
      1. anil

        yes i compared both the source code
        till i’m unable to do that’s what i’m asking you
        what you are uploaded its upto just only login and register
        what i’m asking is that after register and login every user after login he can add a some part of data like contacts to particular category like i’m doing on contacts when i’m trying to add contacts its just when i am clickin on submit it want to show me a dialog that contct adding succed and it should store on db but its showing only dialog succeded but not storing in db that my mistakes to know on my project and you said compare with your project i did that and my db connections are properly connected to code
        if you are able to see my projet send me a reply through mail where i can attach my file
        [email protected] as you said i tried to send mail to this but it is not able to send the server is rejecting

        anil ([email protected])

        Reply
  4. hardik patel

    Hi Ravi,

    This was working perfectly for me. but can you help me with how to add session for authenticated user and how to create profile page of individual user that logged in?

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Hardik,

      To create profile page of individual user, you can use last piece of code.
      To add session,
      in LoginServlet.java modify the following code(32nd line onwards) as follows
      if(userValidate.equals(“SUCCESS”))
      {
      HttpSession session = request.getSession(false);
      if(session!=null)
      request.setAttribute(“userName”, userName);
      ….

      And you would need to give a hyperlink to “logout” in Home.jsp to close or invalidate the session.
      Add following lines either in servlet or JSP

      session.removeAttribute(“userName”);
      session.inValidate();

      Reply
  5. Saumil S. Soni

    I’m still subscribed to this post because each time I receive an email saying someone commented on the post I feel nostalgic because it reminds me that it all began from this post as after reading this I was able to create my final year project in Java MVC with database connectivity(instructor was really impressed that I used MVC framework). I almost laugh when I read my comment which I wrote because of a trivial issue. Its been more than 2 years since then and I have developed a lot of projects using the MVC framework taught in this tutorial. I would like to thank you once again from the heart for writing this tutorial. Great Job!

    Reply
    1. Ravi Bandakkanavar Post author

      Haha. Great experience Saumil. I just revisited through your comment too :)
      Thanks for your valuable feedback.
      Thanks for visiting again and sharing your experience.
      Keep visiting :) . Hope few things have changed here :)
      Would you like to share your few project codes and help newbies here? The posts will be shared by your name and you can communicate with new people here. Let me know.

      Reply
  6. manjunath

    hi ravi
    this is manjunath
    i already requested u for somthing in november 21st 2015
    i dint get feed back
    plz reply

    i copied that text of request and pasted below once again.just see once

    yes ravi.sorry for late reply.
    ya i want one more example on mvc.but it must be like storing and retrieving information
    of employees along with their profile picture.
    for example…If we store information like name,age,emp id,name_of_department ( java ,testing,php,Dot_net,etc) and their profile picture in database.then we must retrieve that data in the form of table according to name_of _department. i.e if we retrieve java employees data,it should be in a tabular form containing only java employees along with their profile picture.
    can u do this plzzzzzzzzzz.
    it will help lot of people like me.

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Manjunath,

      Sorry. I was busy during this time so may have missed it.

      To insert details of an employee, you need to write the code using html tags like input box, select, option etc. You need to create a form either in html or JSP page. This is same like Login.jsp.

      To store images in the database the type of the table element should be BLOB and you can use the following code for insertion

      ps = con.prepareCall("insert into student_profile values (?,?)");
      ps.setInt(1, 101);
      is = new FileInputStream(new File("Student_img.jpg"));
      ps.setBinaryStream(2, is);
      int count = ps.executeUpdate();

      You can use any of the following code to display the data in tabular form
      http://krazytech.com/home/java-program-to-display-arraylist-elements-in-jsp-using-for-loop
      http://krazytech.com/programs/java-program-to-display-arraylist-elements-in-jsp-using-iterator

      Let me know for any issues. Posting this example is a great idea. I will post it at my free time.

      Reply
  7. Shanmukhhi

    Hi Ravi,
    I am tried this example but i got error i.e, “HTTP Status 404 – /MVC/LoginServlet” .How can i solve help me

    Reply
    1. Ravi Bandakkanavar Post author

      Hi,

      Have you placed the web.xml in the right place? Have you verified the spelling of the title pages?
      You can mail me the code. I will help you to debug this error for you.

      Reply
  8. zmrrockz

    hey thanks a lot it was a very helpful example , greatly done by you . if possible please include the registration process in the same example with the code .. please i badly need it

    Reply
  9. Maha

    hi
    i tried registration page but it n’t work please help me in registration dao and registration controller classes and i registering the based on mobile

    Reply
  10. rahul

    when ever i open my sts then i getting this error again and again how can i resolve it and the error is

    Reply
  11. Bunny

    can we write dbconnection using JdbcTemplate in above example?.. i think we need not to write Connections and statement using JdbcTemplate. actually im new to spring.. if we can plze tel me how?

    Reply
  12. ishika

    hello ravi,
    can you please help me with the same login code but if i want to validate username and password from the database (postgresql) and if correct then another page is opened else message “incorrect username/password” is displayed.

    thank you.

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Ishika,

      The code in this post works exactly the way you want it.

      The following code displays the error message if log-in gets failed otherwise the user will be redirected to Home.jsp page.
      < %=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%>

      Reply
  13. Maha

    hai ravi garu
    can you help how to create registration page using mvc with servlets and jsp with sql db

    Reply
    1. Ravi Bandakkanavar Post author

      Hi,

      Registration is more simpler process. You just need to insert data into the database. You can also check for duplicate users i.e. if the user is already registered. I will help you with that.

      Basically
      Login.jsp will become Register.jsp
      LoginServlet ->RegisterServlet
      LoginDao -> RegisterDao (Main bsiness logic should be written here)

      Soon after registration you should send the user to a page and where he should be asked to login with his credentials.

      Reply
      1. Maha

        Good morning…
        hai
        can you help me one thing please
        i have tried an application like sending email using servlets
        i have written sendingmail.servlet and mailutility.servlet in web.xml also i configure. but compose.html am using rich text box to editing the text want we want but text box is working but email is not sending

        Reply
      2. Maha

        both registration and login will placed same project just few java pages added

        Reply
  14. manjunath

    hi ravi,
    this is manjunath.
    i got a problem while runniing this example .after putting username and password in login.jsp page
    it is throwing a http status 500- error.how can i resolve it ?plz help me . go through the error that i got and given below.

    HTTP Status 500
    type Exception report
    message

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    java.lang.NullPointerException

    Reply
    1. Ravi Bandakkanavar Post author

      Hi,

      Have you configured other pages LoginDao.java, LoginServlet.java as well ?
      Are you using eclipse for execution? Do maintain the structure as specified and import the dependent files in each page.

      Please reply if still error exists

      Reply
      1. manjunath

        hi ravi,
        yes i am using eclipse helios. my problem is resolved by adding mysql connector jar file into the lib folder of web-inf.Before it was added into the project Library using buildpath but it was’nt worked for me.when i saw the structure in ur eaxample it was in lib folder.finally i imported that in to lib then it worked .any way thanks for ur reply and ur example.its realy good for mvc learners.

        Reply
          1. manjunath

            HI ravi.
            can u tellme that why u have written some script tag in login.jsp
            i.e

            __CF.AJS.init1();

            and also plz tellme about below line .

            Reply
          2. manjunath

            yes ravi.sorry for late reply.
            ya i want one more example on mvc.but it must be like storing and retrieving information
            of employees along with their profile picture.
            for example…If we store information like name,age,emp id,name_of_department ( java ,testing,php,Dot_net,etc) and their profile picture in database.then we must retrieve that data in the form of table according to name_of _department. i.e if we retrieve java employees data,it should be in a tabular form containing only java employees along with their profile picture.
            can u do this plzzzzzzzzzz.
            it will help lot of people like me.

            Reply
  15. suresh

    hi ravi
    please help me i got didn’t get any error but
    but didn’t get output also..
    405 HTTP Status 405 – HTTP method GET is not supported by this URL

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Saurabh,

      Where are you trying it ?
      GET method is supported by most of the browsers or applications. You can also try using POST method in the login page. Let me know what happens.

      Reply
  16. ramya

    i m getting error at String userValidate =loginDao.authenticateUser(loginBean);
    Please help me

    Reply
  17. Goodness

    Hello Ravi,

    Thanks for this wonderful post.

    I am a novice here… i am looking at developing a desktop application but using the MVC framework.

    Can you do another log in example but this time using desktop application connecting to mysql database?

    Reply
    1. Ravi Bandakkanavar Post author

      Yes you can use any DB. Your DBConnection.java should be modified as per your DB server. You will have to use Oracle driver.

      Reply
  18. Arjun

    Hi Ravi,

    I am new to Java and learning it.I am planning to build a small website as my hobby and probably host it.So which java framework is the best for doing this.
    Can i do the above on my laptop and from where i can download the MySQL

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Arjun,

      You can use this code. MySQL can be downloaded from its official website.
      MVC is the standard method to follow.

      Reply
  19. uday

    hii Ravi, thanks for your explanation. i got an error when am accessing a servlet page from my login.jsp
    please clarify this problem…thanks

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Uday,

      Please explain what kind of error.

      You have to mention the correct name of your servlet page in the action tag of login.jsp.
      action=”LoginServlet”

      Plus please configure web.xml as well. Give the full class name in the tag.
      com.mvc.controller.LoginServlet

      Reply
  20. salapso

    Hi ravi,

    Good and informative post. May I request to you what is the table name, and its fields you have been used for this program.

    Thanks in advance.

    Reply
  21. ramu

    how to invalidate a session in springMVC….tell me one example.. Thanks in advance

    Reply
    1. Ravi Bandakkanavar Post author

      In LoginServlet.java modify the following code(32nd line onwards) as follows
      if(userValidate.equals(“SUCCESS”))
      {
      HttpSession session = request.getSession(false);
      if(session!=null)
      request.setAttribute(“userName”, userName);
      ….

      And you would need to give a hyperlink to “logout” in Home.jsp to close or invalidate the session.
      Add following lines either in servlet or JSP

      session.removeAttribute(“userName”);
      session.inValidate();

      Reply
  22. ramu

    develop spring mvc example for employee registration login and profile view. shd use spring mvc and JDBC

    Reply
  23. Tirthankar Mondal

    One of the best explanation……..It helps me lot……..Thank You…….

    Reply
  24. Paras

    Hey..Thanx for the post!! Working fine with me…i m facing just 1 problem..if user name or password is wrong then the error msg is not coming on the screen..! I ll be glad if u can help me with this..Thanx again.

    Reply
  25. Saumil

    Hey Ravi nice explanation man, but I’m facing a little problem here. When I run the login.jsp page and click on ‘login’ button then I’m getting Error-404 and the URL of this error page is ‘http://localhost:8080/Proj1/pages/LoginServlet’.
    My ‘login.jsp’ page is in ‘web-inf/pages’ and the LoginServlet is in a separate package outside the web-inf named ‘controller’. Then why does my URL is showing ‘pages/LoginServlet’.

    Reply
    1. Saumil

      Sorry man, my error is resolved by taking ‘login.jsp’ and ‘home.jsp’ outside the web-inf folder and pasting it directly within the web pages folder.
      Thanks.

      Reply
  26. misc

    I tried it in eclipse and ad one issue. Warning that setters and getters from LoginBean are not visible. I corrected that error by making them public.
    My other issue is lack of SQL code for database. Where can I find it?
    Otherwise great example. Tnx

    Reply
    1. Ravi Bandakkanavar Post author

      Hi,

      Yes. in LoginBean class while defining the variables it must be private and the return parameter for setters and getters must be public. Thanks for identifying the problem.

      SQL code for connection is present. This code is to connect to SQL server. for oracle we need to modify it as given below(after first code).

      public class DBConnection {
      public static Connection createConnection()
      {
      Connection con = null;
      String url = “jdbc:mysql://localhost:3306/ravi”; //for SQL and oracle or any other db server this url differs
      String username = “root”; //username of database user
      String password = “root”; //password

      try
      {
      try
      {
      Class.forName(“com.mysql.jdbc.Driver”);// differs from DB server to server
      }
      catch (ClassNotFoundException e)
      {
      e.printStackTrace();
      }
      con = DriverManager.getConnection(url, username, password);
      }
      catch (Exception e)
      {
      e.printStackTrace();
      }

      return con;
      }
      }

      Code for oracle connection.

      public class DBConnection {

      public static Connection createConnection() {

      Connection con = null;
      String url = “jdbc:oracle:thin:@172.25.192.71:1521:javadb”;
      String username = “H123ORAUSER4D”;
      String password = “tcshyd”;

      try
      {
      try
      {
      Class.forName(“oracle.jdbc.driver.OracleDriver”);
      }
      catch (ClassNotFoundException e)
      {
      e.printStackTrace();
      }
      con = DriverManager.getConnection(url, username, password);

      }
      catch (Exception e)
      {
      e.printStackTrace();
      }

      return con;

      }
      public static void closeConnection(Connection con) {
      try {
      con.close();
      } catch (SQLException e) {
      e.printStackTrace();
      }
      }
      }

      Reply
  27. Mirzan

    Hi ravi the login works well for users table , when i change it to employee_Register table name the output throws an user Invalid user credentials validation error where the userName and the password field remains in 4th and 5th field (taken place)in the employee table, can you provide a solution for this issue

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Mirzan,

      Hope you have maintained the same column names for your employee_Register table also.
      Definitely I will help in debugging your code. Could you just paste your block of code here ? so that it will be easy for me to isentify the issue.

      Reply
  28. shivansh

    please kindly explain how to run this code in eclipse.
    Options were Run as ->java applet
    ->java application
    ->eclipse app
    ->osgi app

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Shivansh,

      You should go for Java application.
      All the programs which uses web languages like html, jsp should be run as java application.

      Reply
  29. Ramakrishna

    if more than one user name and password exists in the database means is this code works ? i thing query got some errors

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Ramakrishna,

      This query works perfect.

      while(resultSet.next()) // Until next row is present otherwise it return false
      {
      userNameDB = resultSet.getString(“userName”); //fetch the values present in database
      passwordDB = resultSet.getString(“password”);
      }

      As it is in the loop it handles multiple records.
      I think you have not used while loop. Compare your code, if you do not get contact me once again.

      Reply
      1. Ravi Bandakkanavar Post author

        Hi Ramakrishna,

        Yes we need to make a small change to make this code work for multiple users.
        We just need to check for users within the while loop. Sorry I did not check while replying to you previously.

        while(resultSet.next()) // Until next row is present otherwise it return false
        {
        userNameDB = resultSet.getString(“userName”); //fetch the values present in database
        passwordDB = resultSet.getString(“password”);

        if(userName.equals(userNameDB) && password.equals(passwordDB))
        {
        return “SUCCESS”; ////If the user entered values are already present in database, which means user has already registered so I will return SUCCESS message.
        }
        }

        Reply
  30. Oscar

    Excelent post….. I have a question if I have a sqlserver DB, what is the code in the DBConnection.java ???

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Oscar,

      The one which I have used here is a connection to MySQL only. You can use the same. For MySQL you need to add one extra jar file. MySQLCOnnector.jar. You can download the same online.

      Connection con = null;
      String url = “jdbc:mysql://localhost:3306/ravi”; //for SQL and oracle or any other db server this url differs
      String username = “root”; //username of database user
      String password = “root”; //password

      Class.forName(“com.mysql.jdbc.Driver”);// differs from DB server to server

      For Oracle it will differ again.

      Reply
  31. JayTai

    This is really a great example, but I’m having some problems. I’m running this in Netbeans and facing the following error when running:

    java.lang.NullPointerException
    com.mvc.dao.LoginDao.authenticateUser(LoginDao.java:26)
    com.mvc.controller.LoginServlet.doPost(LoginServlet.java:30)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

    Reply
    1. Ravi Bandakkanavar Post author

      Hi JayTai,

      Did you create the files LogiDao.java in the package com.mvc.dao and LoginServlet.java in the package com.mvc.controller?

      And reqyest must be sent to these files from some jsp. I think you are not passing any values here so its throwing null pointer exception.

      Please try it properly and contact me if you still have any doubts.

      Reply
    2. Saumil

      Hey JayTai, I was facing similar problem, but it was resolved when I included the mysql.jar file in my netbeans.

      Reply
  32. puja

    good job.Will help a lot of people.Thanks for taking the initiative.

    Reply
  33. sampath

    This use a very useful peace of project which I found very helpful to start with J2EE web development. Thanks for the project and one who did this for novice people.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *