Suggested articles for you:

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

  1. Arhaan

    Actually I try using single Controller..
    I face some Problem like When i register it, its work fine…
    but in case of login Error arise on RegistreBean in controller..
    Here no need of RegisterBean in case of login..
    But I face problem in single controller, how can i use both Beans object in controller…
    and how login.jsp page connect to LoginBean object inside the same controller…??

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Arhaan,

      You can use a common servlet, common bean, common DAO class. Use separate methods.

      Create a single bean class with all the user details. During login just set and get username and password.

      You can refer to my comments to Manasa on how to segregate your functionality in a single servlet.

      Reply
  2. Arhaan

    Thankew Sir.. alot for this program ..
    but i need this one…
    Please give me the Register & Login application both in Java using MVC2 and MySQL with single controller..

    Reply
  3. Dinesh

    Sir, Thanks you so much for help me.I dont have any word for you that much help got from this example.

    Reply
      1. Manasa

        Hi Ravi,

        I have uploaded image in a folder and stored its path in the database. While displaying it, I am accessing the path from database and giving it in anchor tag so when it is clicked the image should get open. But it is not. I have checked for the path and the path is exactly correct. And I have tried to just display image by using img tag, it works fine in eclipse browser but when I open it in chrome it does not get displayed.
        I am not understanding this behaviour. Please give any idea. The path that I am storing in the database is correct and I want the image to get open when it is given in anchor tag.

        Thank You.

        Reply
  4. Manasa

    Hi,
    Consider after successful login, I will redirect the page to home.jsp where the person who has logged in can enter the employee details. To do this should I have create a separate servlet and DAO file? How to do this? Please give me a brief idea.

    Thank you.

    Reply
    1. Ravi Bandakkanavar Post author

      Good question.
      It depends on what operation you would like to implement. If you would just want to display a form where user can enter details and submit, for this you can have a JSP and after submitting, you could either go to same servlet but call a different method there and then the DAO class. There are many ways to do this.

      On the other hand, if you just want to display some results, you could do this using JSP tags either on the same JSP or a link to another one.

      Reply
      1. Manasa

        Hi Ravi,

        I created separate servlet and DAO files to add employee details into the database. Worked fine and was able to understand the flow.

        Thank you.

        Reply
      2. Manasa

        And also I am not able to understand request.getAttribute() and setAttribute. Can you give an example and explain?

        Thank you.

        Reply
      3. Manasa

        Hi Ravi,

        Whenever we call servlet using form, control automatically goes to doPost() in servlet. How can we call a specific function in servlet as it contains only doGet() and doPost()? If we can do that please explain us how?

        Thank you.

        Reply
        1. Ravi Bandakkanavar Post author

          Hi Manasa,

          Very good question and welcome back.
          You can have only the methods which are present in the parent class i.e. HttpServlet.

          The HttpServlet class contains the methods – doGet, doPost, doPut, doDelete, init, destroy, getServletInfo.

          You can follow one of these 2 methods to customize your code.
          1. For Get method:
          Inside a JSP:
          /AddTestServlet?type=createTest">Create Test
          Inside a servlet:
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String type=request.getParameter("type");
          if (type.equals("createTest"))

          For Post method:

          - in JSP
          In the Servlet:
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String type=request.getParameter("type");
          if(type.equals("deleteTest"))

          2. You can redirect your requests to a common method and implement your logic.
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          process(request,response);
          }
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          process(request,response);

          public void process(HttpServletRequest request,HttpServletResponse response)
          { ......
          }

        2. Manasa

          Hi Ravi,

          I have added a photo to the database and able to access and display it. But when I want to edit it, there occurs a prblm. In jsp I have dis code and in action i am giving control to EditServlet.

          //for displaying photo and in source i have given control to ImageServlet so that image can be displayed

          photo
          <img src="ImageServlet?id=” name=”editphoto” height=”50px” width=”50px”>

          //for changing photo

          Change photo here

          When i use this code, I have to edit photo otherwise it stores null in the database. I mean if I add a new photo it takes that photo and stores it in database otherwise if I change other parameters and not the photo it takes null. I am accessing the ‘file’ in the EditServlet and updating it. If I give a new photo over there it works allright but when i dont want to edit it, it takes null. I am getting to know that as I am not giving any values,it takes null but I dont want that to happen. I want previous image to be displayed. How can I give the condition for it. I thought since I have given control to the ImageServlet for displaying, it will store the previous image even though I dont edit it. I hope my question is clear.
          I need help in this.

          Thank you.

        3. Manasa

          photo
          <img src="ImageServlet?id=” name=”editphoto” height=”50px” width=”50px”>

          Change photo here

          This is the code

        4. Manasa

          Hi Ravi,

          Thanks I got how to call another function in the servlet. When we are calling like this can we pass the data to it? I mean we are calling process(request,response) so here can we pass the data to process()?

          Thank you.

    2. Manasa

      Hi Ravi,

      I have a doubt. Consider that I have added registered users details successfully into the database and I have fetched the details from database and displayed and also I have given modify and delete button to each of it. Now when I click modify of particular row that particular name and password should be displayed. For this I am doing all the database operations in the jsp page and displaying it. Is this wrong pattern of mvc? If I have to user servlets how can I do that?

      Reply
      1. Ravi Bandakkanavar Post author

        Hi Manasa,

        You can edit it in the JSP page. There is no need to traverse through servlet for every small operation.
        If you want to go via servlet, when you click on modify button, you need to have a link to servlet Modify. From here you can implement the same logic.

        Reply
        1. Manasa

          What is @webservlet? When this statement is there in servlet, whatever mapping i do in web.xml does not affect anything. I mean the servlets dont even run? Why is this?

        2. Ravi Bandakkanavar Post author

          Hi Manasa,

          @WebServlet is the annotation used to declare a servlet.
          I don’t see it in the LoginServlet.
          I think it is added by Eclipse automatically in your case. I am not sure about the issue you are facing.

          Every new servlet needs to be mentioned in the web.xml. Whenever a servlet gets compiled, the web.xml is referred.

  5. Manasa

    Thanks Ravi.
    It worked fine for me. This really has helped me a lot in how to go about in mvc coding. It has solved lots of confusions that I had in mvc coding.

    Reply
  6. Manasa

    Hi,
    I am lately responding to this post but it was very helpful for me in understanding mvc. I observed that you hav created packages like com.mvc.bean. Is it necessary to give the same names? Can we the desired name?
    And also I am getting this error
    java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/login
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at model.LoginDao.authenticate(LoginDao.java:31)
    at controller.loginservlet.doPost(loginservlet.java:46)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)

    Can you help with this?

    Reply
  7. Raksha

    Hi Ravi,
    same structure i followed but it is not running Login.jsp page, i checked my web.xml file also. Please help me

    Reply
  8. saurav mihsra

    sir i have create my sign up and login page as well as my appointment page in html5 .. i have create database table for appointment and sign up now how to connect it to netbean 8.2

    Reply
  9. Rinal

    Hi ravi,
    Can you please tell me, how to connect it with the oracle database?
    It gave me an error of null pointer exception.
    So please help me out as soon as possible?

    Reply
    1. Ravi Bandakkanavar Post author

      Hi Rinal,

      You will have to change two things to use Oracle database.
      1. Replace following in DBConnection.java
      Class.forName(“oracle.jdbc.driver.OracleDriver”);
      Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:ravi”); //port and DB name should be used as per your details.
      2. Place ojdbc14.jar file in lib folder

      Reply
      1. hanife kurnaz

        When i run login.jsp and click the login button error is java.lang.NullPointerException
        com.mvc.dao.LoginDao.authenticateUser(LoginDao.java:24)
        com.mvc.controller.LoginServlet.doPost(LoginServlet.java:33)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        when i run register.jsp and click the register button error is
        java.lang.NullPointerException
        com.mvc.dao.RegisterDao.registerUser(RegisterDao.java:25)
        com.mvc.controller.RegisterServlet.doPost(RegisterServlet.java:34)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        :(:(

        Reply
        1. Ravi Bandakkanavar Post author

          Hi Hanife,

          Have you included web.xml and added it under WEB-INF folder ?

          Provide the full reference path for .
          com.mvc.controller.LoginServlet

          Let me know if you still face any issue.

        2. hanife kurnaz

          web xml :

          Mvc

          Login.jsp

          LoginServlet
          com.mvc.controller.LoginServlet

          LoginServlet
          /LoginServlet

          RegisterServlet
          com.mvc.controller.RegisterServlet

          RegisterServlet
          /RegisterServlet

          </web-

        3. Ravi Bandakkanavar Post author

          Hanife,

          What IDE are you using to execute this code ? If you are using eclipse, did you maintain the package and other classes same as mentioned here?

          Initially when you sumbit login.php, the request will be sent to LoginServlet.java and post method is used here.
          [code - form name="form1" action="LoginServlet" method="post"]

          Please put some log statements(System.out.println()) within servlet page and try to trace the code execution. Use multiple debug statements.

          Let me know what you see

        4. Abhinav Sharma

          simple copy the servlet jar and my connection jar in a lib folder instead of importing it to libary it ll work

        5. Priyanka Singh

          Even i am facing the same problem.Please help me to solve this issue

  10. 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.

    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
  11. 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
  12. 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. anil

          i sent u a mail
          plz check it and give me answer

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

        3. 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

        4. 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

      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
        admin@krazytech.com as you said i tried to send mail to this but it is not able to send the server is rejecting

        anil (anil.kakara@gmail.com)

        Reply
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
        1. Ravi Bandakkanavar Post author

          To send email, have you configured SMTP host properly? through what channel are you trying to send mail?
          Is it working with plain text ?

      2. Maha

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

        Reply
  23. 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 .

        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.

  24. 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
  25. ramya

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

    Reply
  26. 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
  27. 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
  28. 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
  29. 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
  30. 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
  31. ramu

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

    Reply
  32. Tirthankar Mondal

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

    Reply
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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
  41. puja

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

    Reply
  42. 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

Did it help? Comment here..