This Java login application follows MVC architecture and consists of Java servlets, JSPs. It uses MySQL database server to refer to the user details. The input fields are validated using javascript.
What is a Model View Controller architecture?
The model (DAO) consists of application data and business rules, and the controller (Servlet) acts as an interface between views and model. It mediates input, converting it to commands for the model or view. A view (JSP) can be any output representation of data, such as a chart or a diagram, generally HTML or JSP page.
Here DAO is the Data Access Object – This part concentrates on business logic and database server connections and operations.
Use any IDE – Integrated development environment to minimize your work. If you haven’t started using any IDE, go get one. You will fall in love with it. I would recommend you to use Eclipse for Java applications. Link to download Eclipse. It is an open source tool.
This application is explained thoroughly with appropriate comments and tested in Eclipse IDE. Please write comments if you find any difficulty while understanding the application.
Suggested Read:
It is advised to segregate different components in a standard directory structure as shown below. Start your programming with New Project -> dynamic web application project type.
Login details are forwarded to LoginServlet from Login.jsp page. When you click on Login button the request is forwarded to the page which is mentioned in action tag of the form so here the request will be forwarded to LoginServlet.java class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
//Login.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login</title> <script> function validate() { var username = document.form.username.value; var password = document.form.password.value; if (username==null || username=="") { alert("Username cannot be blank"); return false; } else if(password==null || password=="") { alert("Password cannot be blank"); return false; } } </script> </head> <body> <div style="text-align:center"><h1>Login application in Java using MVC and MySQL </h1> </div> <br> <form name="form" action="LoginServlet" method="post" onsubmit="return validate()"> <!-- Do not use table to format fields. As a good practice use CSS --> <table align="center"> <tr> <td>Username</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" /></td> </tr> <tr> <!-- refer to the video to understand request.getAttribute() --> <td><span style="color:red"><%=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%></span></td> </tr> <tr> <td></td> <td><input type="submit" value="Login"></input><input type="reset" value="Reset"></input></td> </tr> </table> </form> </body> </html> |
1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
//LoginServlet.java package com.mvc.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mvc.bean.LoginBean; import com.mvc.dao.LoginDao; public class LoginServlet extends HttpServlet { public LoginServlet() { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Here username and password are the names which I have given in the input box in Login.jsp page. Here I am retrieving the values entered by the user and keeping in instance variables for further use. String userName = request.getParameter("username"); String password = request.getParameter("password"); LoginBean loginBean = new LoginBean(); //creating object for LoginBean class, which is a normal java class, contains just setters and getters. Bean classes are efficiently used in java to access user information wherever required in the application. loginBean.setUserName(userName); //setting the username and password through the loginBean object then only you can get it in future. loginBean.setPassword(password); LoginDao loginDao = new LoginDao(); //creating object for LoginDao. This class contains main logic of the application. String userValidate = loginDao.authenticateUser(loginBean); //Calling authenticateUser function 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. } else { request.setAttribute("errMessage", userValidate); //If authenticateUser() function returnsother than SUCCESS string it will be sent to Login page again. Here the error message returned from function has been stored in a errMessage key. request.getRequestDispatcher("/Login.jsp").forward(request, response);//forwarding the request } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
//LoginDao.java package com.mvc.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mvc.bean.LoginBean; import com.mvc.util.DBConnection; public class LoginDao { public String authenticateUser(LoginBean loginBean) { String userName = loginBean.getUserName(); //Keeping user entered values in temporary variables. String password = loginBean.getPassword(); Connection con = null; Statement statement = null; ResultSet resultSet = null; String userNameDB = ""; String passwordDB = ""; try { con = DBConnection.createConnection(); //establishing connection statement = con.createStatement(); //Statement is used to write queries. Read more about it. resultSet = statement.executeQuery("select userName,password from users"); //Here table name is users and userName,password are columns. fetching all the records and storing in a resultSet. 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. } } catch(SQLException e) { e.printStackTrace(); } return "Invalid user credentials"; // Just returning appropriate message otherwise } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//LoginBean.java package com.mvc.bean; //As I have already told it contains only setters and getters public class LoginBean { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } |
We have used the MySQL database server to read user information. You would need to include the dependent JAR (mysql-connector-java.jar) to connect to MySQL server. The database name is customers and the table name is users. If you take a look at the video, we are using the MySQL database server that comes as part of WAMP software (works for windows OS). It is a freeware, just download, install and use it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//DBConnection.java package com.mvc.util; import java.sql.Connection; import java.sql.DriverManager; public class DBConnection { public static Connection createConnection() { Connection con = null; String url = "jdbc:mysql://localhost:3306/customers"; //MySQL URL and followed by the database name String username = "root"; //MySQL username String password = "root123"; //MySQL password try { try { Class.forName("com.mysql.jdbc.Driver"); //loading mysql driver } catch (ClassNotFoundException e) { e.printStackTrace(); } con = DriverManager.getConnection(url, username, password); //attempting to connect to MySQL database System.out.println("Printing connection object "+con); } catch (Exception e) { e.printStackTrace(); } return con; } } [/java] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//web.xml //this file is known as deployment descriptor. It contains the servlet and other configuraion details <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>LoginMvc</display-name> <welcome-file-list> <welcome-file>Login.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.mvc.controller.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>LogoutServlet</display-name> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.mvc.controller.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/LogoutServlet</url-pattern> </servlet-mapping> </web-app> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//Home.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Home Page</title> </head> <body> <center><h2>Home Page</h2></center> Welcome <%=request.getAttribute("userName") %> <!-- Refer to the video to understand how this works --> <div style="text-align: right"><a href="LogoutServlet">Logout</a></div> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//LogoutServlet.java package com.mvc.controller; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); //Fetch session object if(session!=null) //If session is not null { session.invalidate(); //removes all session attributes bound to the session request.setAttribute("errMessage", "You have logged out successfully"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Login.jsp"); requestDispatcher.forward(request, response); System.out.println("Logged out"); } } } |
Many users were asking for the role-based login application. I have made a post recently for the Session and Role based Java Login example.
Hi Rave,
I think bean must implement Serializable according to the document.
Hi sir
will this code run in derby database
Hi Shakeel,
You need to modify only DBConnection.java file to make it work with Derby DB.
Also, add the corresponding JAR file.
sir can you say about the modification in DBConnection.java file
I added the jar file
Hi,
Change the following lines.
String url = “jdbc:derby://localhost:3306/customers”;create=true;
Class.forName(“org.apache.derby.jdbc.EmbeddedDriver”);
Hi,
Change the following lines.
String url = “jdbc:derby://localhost:3306/customers;create=true”;
Class.forName(“org.apache.derby.jdbc.EmbeddedDriver”);
Hi Ravi, I am encoutering an issue when I try to run on the server I get an error “Server Tomcat v 8.0 Server at localhost failed to start.”
I need your help please.
Here is my web.xml maybe it comes from here.
Untitled
login.jsp
LoginServlet
LoginServlet
com.cw.servlets.LoginServlet
LoginServlet
/LoginServlet
LogoutServlet
LogoutServlet
com.cw.servlets.LogoutServlet
LogoutServlet
/LogoutServlet
*.jsp
/WEB-INF/taglibs.jsp
Hi Bob,
The tomcat server issue has nothing to do with your web.xml.
Can you try deleting your Tomcat server and adding once again?
Hii
I am executing the above code as same it.
But i have error – The requested resource is not available.
can you please help me
Hi Preet,
It could be the issue with your tomcat server. Did you add the tomcat web server and run your java web project?
i am having a problem of http status 404 error for glassfish server. i already google but it doesnt work, can you help me ?
Hi Miss,
Did you receive this error when you submitted the Login details?
404 error occurs when the resource is not available. It could be the case that it is not able to locate your LoginServlet.java class. Can you try to fix it? Compare the web.xml as well.
ok thank you
how a jsp page can be converted into pdf on clicking the button in jsp page(on clicking the button it should convert to pdf)sir plz help me
Hi Nikhil,
Do you want to convert your JSP page to PDF? or want to give a link of a PDF in your JSP?
The first one may not be possible easily.
For the second one, you will have to upload the PDF file in your server and include the path(link) to the PDF in your JSP. Whenever you click on the link the PDF gets opened on the browser. You can make it open in the new tab.
sir can you give a small example so that i can understand easily or any website link
HTTP Status 500 error, java.lang.ClassNotFoundException: com.mysql.jdbc.Driver,at com.mvc.util.DBConnection.createConnection(DBConnection.java:18)
Hi Kiran,
Did you include mysql-connecior-java.jar?
What database server are you using?
hi sir,
i included mysql-connector-java.jar .i have using mysql database
Hi Kiran,
I there could be some spelling mistake with the line
Class.forName("com.mysql.jdbc.Driver");
Can you copy DBConnection.java class as is and try.
Yeah I changed my root password to root123. But I still have the same problem…
Can you work to match your database username and password with the username and password which you have given in your DBConnection.java.
Hi Ravi,
How can I access data from mysql database in lifo manner? I cannot access it through id(i.e using desc in query) because id is randomly generated. But if I access it through date the order is not proper.
And also in your blog when somebody asks a question and when you reply for it, your reply will come after that particular question. I mean the questions and answers are sorted. How can this be achieved? Can i do this in jsp?
Thank you.
Hi Manasa,
If you use order by date desc, it should return the latest inserted record on the top. It works always.
If you still want to go for some other method, You can insert the records in the arraylist and sort it later. You can also go for Queue.
Regarding Comments:
This is wordpress platform built using PHP. It is handled through CSS I believe.
You can also implement it using JSP and CSS. You should define a different class and define separate placing for replies. Not a straight-forward process though.
Thank you for the visit after a while :)
package com.elintsys.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection
{
public static Connection createConnection()
{
Connection con=null;
String url = “jdbc:mysql://127.0.0.1:3306/testdata”;
String username=”root”;
String password=”root”;
try
{
Class.forName(“com.mysql.jdbc.Driver”);
System.out.println(“*** Registration Success ***”);
con=DriverManager.getConnection(url+username+password);
System.out.println(“Printing connection object “+con);
System.out.println(“*** Connection Created From DBConnection ***”);
}
catch(Exception e)
{
System.out.println(e.getMessage()+” *** Check DBConnection.java file ***”);
}
return con;
}
}
This is my Code. But I have Problem when I’m trying to connect [Access denied for user ”@’localhost’ (using password: NO)] What I have to do? Pls give brief explaination…
Hi,
Could you please change the password to root123 and try.
[Access denied for user ”@’localhost’ (using password: NO)]
What I have to do?
Yes. I’m talking about Credentials
Use the following command then your code will work.
SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘root123’);
I’m having error like this [org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/login/HomeControll] in DispatcherServlet with name ‘appServlet’]
please help me….
Hi Viji,
If your servlet name is appServlet then your URI must be /appServlet.
where I want to change that modification?
Are you using the same code?
If yes, you will have to change the action element in the form in Login.jsp.
I’m having error like this [Communications link failure] and [Last packet sent to the server was 0 ms ago.] what I have to do?
Not a familiar error.
What IDE are you using?
Can try going through the following video and follow the steps exactly how it is mentioned.
https://youtu.be/_WLeWa7mjHw
I’m Using Eclipse Neon IDE. now I’m having this kind of error[Access denied for user ”@’localhost’ to database]
You need to change the credentials in the DBConnection.java as per your MySQL server credentials.
Send The Source Code Also…..
You can copy the code from this post.
How Can I do that? Please explain it and give some example…
Are you talking about changing credentials?
yaa its very helpful but do some more examples on this concepts sir
Thanks for your comments Nikhil.
Yes. I need to post more such code. Are you looking for any specific thing?
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…??
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.
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..
Great example sir . Thank you so much :)
You are welcome.
Thanks Sajjad.
Sir, Thanks you so much for help me.I dont have any word for you that much help got from this example.
Thanks, Dinesh.
You are always welcome here. I am going to write more such examples.
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.
Manasa,
I have to look into the code to find out the issue. Can you email your code to me?
Hi Ravi,
I need you email id.
Thank you.
contact@krazytech.com
mansa can you send same code to my mail because i am also facing same problem
nikhilvooturi57@gmail.com
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.
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.
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.
Great.!! Good luck ahead!
And also I am not able to understand request.getAttribute() and setAttribute. Can you give an example and explain?
Thank you.
It works as a key-Value pair.
In the servlet, you are writing
request.setAttribute("userName", userName)
and you are accessing this value via key “userName” in the Home.jsp
request.getAttribute("userName")
Go to this link, it is explained here. https://youtu.be/_WLeWa7mjHw?t=5m10s
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.
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:
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)
{ ......
}
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.
photo
<img src="ImageServlet?id=” name=”editphoto” height=”50px” width=”50px”>
Change photo here
This is the code
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.
Yes, Manasa.
You can do that.
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?
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.
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?
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.
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.
You are welcome Manasa.
I’m glad it helped you.
You may like to go through role based login application as well at this point – http://krazytech.com/programs/session-role-based-java-login-example
Video- https://youtu.be/swdx5g0X1hk
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?
Hi Manasa,
You need to copy mysql-connector jar.
You can give any name to packages.
Hi Ravi,
same structure i followed but it is not running Login.jsp page, i checked my web.xml file also. Please help me
Hi Raksha,
Could you please brief me a little more about your issue?
Have you added dependent JAR files?
This video may help you in some ways – https://www.youtube.com/watch?v=_WLeWa7mjHw.
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
did you use Java pages or HTML pages?
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?
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
Thank you. it worked fine for me
Great Sudha. You are always welcome here..
error :(:(
Hi Hanife,
What error are you getting ?
It is a working code.
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)
:(:(
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.
web xml :
Mvc
Login.jsp
LoginServlet
com.mvc.controller.LoginServlet
LoginServlet
/LoginServlet
RegisterServlet
com.mvc.controller.RegisterServlet
RegisterServlet
/RegisterServlet
</web-
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
Im using Eclipse , and i did same things
Fine. Please have logs enabled and let me know what you are getting.
simple copy the servlet jar and my connection jar in a lib folder instead of importing it to libary it ll work
Thanks Abhinav for this suggestion.
Yes. we can add all dependent files to the lib folder as well.
Even i am facing the same problem.Please help me to solve this issue
Hi Priyanka,
What error are you facing? Have you added required Jar files? I believe the issue mentioned in the main thread is already addressed.
You can also go through following video where each and every step is explained in detail.
https://www.youtube.com/watch?v=swdx5g0X1hk&t=6s
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,
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);//
}
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.
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.
Hi,
Here you go http://krazytech.com/programs/session-role-based-java-login-example
hi…please provide entire code role based login example..thanks
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
Hi Mahadev,
Here you go http://krazytech.com/programs/session-role-based-java-login-example
Can we write JSP MVC web application without using Java beans.
Can u explain me why we use Java beans in JSP MVC?*
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)
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
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.
if u give your email id
i can mail to you
admin@krazytech.com
i sent u a mail
plz check it and give me answer
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
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
Hi Anil,
There must be an error with database connection. What database are you using ? You need to include suitable driver in the lib directory. you can download this one online easily.
To insert data into database you can refer to the following registration post where records are being inserted in the database.
http://krazytech.com/programs/java-registration-page-using-jsp-servlet-mysql-mvc
Let me know for any issues.
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
Hi Anil,
Could you please answer my questions ?
I am trying to help you here. The given code as it should work fine. If you want to compare it, you can also cross verify with following Registration code
http://krazytech.com/programs/java-programs/java-registration-page-using-servlet-mysql-mvc
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)
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?
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();
Hi All,
I have posted an example for Java Registration Page. Please refer the same here http://krazytech.com/programs/java-programs/java-registration-page-using-servlet-mysql-mvc
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!
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.
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.
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.
Hi Ravi,
I am tried this example but i got error i.e, “HTTP Status 404 – /MVC/LoginServlet” .How can i solve help me
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.
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
Sure. I will update the post.
Please refer following post for Java Registration example
http://krazytech.com/programs/java-programs/java-registration-page-using-servlet-mysql-mvc
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
Please refer following post for Java Registration example
http://krazytech.com/programs/java-programs/java-registration-page-using-servlet-mysql-mvc
when ever i open my sts then i getting this error again and again how can i resolve it and the error is
Hi Rahul,
You have not mentioned the error message.
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?
Hi Bunny,
This is not an example with java spring. It explains simple MVC architecture.
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.
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")%>
hai ravi garu
can you help how to create registration page using mvc with servlets and jsp with sql db
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.
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
To send email, have you configured SMTP host properly? through what channel are you trying to send mail?
Is it working with plain text ?
both registration and login will placed same project just few java pages added
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
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
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.
Thank you Manjunath.. I feel overwhelmed with such comments :)
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 .
Hi Manju,
You can ignore it. It does not play any role in simple login page.
can u post one more example ravi.
Hi,
One more Example on MVC?
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.
thankx for this code… it helped alot
You are welcome Kartiki.. :)
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
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.
i m getting error at String userValidate =loginDao.authenticateUser(loginBean);
Please help me
Hi Ramya,
Could you please describe your error ?
Did the method authenticateUser() get called ?
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?
Hi,
To build desktop application you should use java swing. Just interface will differ i.e. login page and rest all will be same.
Refer to the following post to understand swing and build the log-in application.
http://java.dzone.com/articles/htmlcssjavascript-gui-java-0
show me a HTTP Status 404 error
Hi Jeya,
Could you please explain me your requirement.
Can i use Oracle DB in place of MySql
Yes you can use any DB. Your DBConnection.java should be modified as per your DB server. You will have to use Oracle driver.
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
Hi Arjun,
You can use this code. MySQL can be downloaded from its official website.
MVC is the standard method to follow.
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
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
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.
Thank you Salapso,
The table used is users. userName,password : these two columns will work for the project.
how to invalidate a session in springMVC….tell me one example.. Thanks in advance
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();
develop spring mvc example for employee registration login and profile view. shd use spring mvc and JDBC
Yes Ramu.
One of the best explanation……..It helps me lot……..Thank You…….
Thank you Tirthankar for your comment.
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.
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’.
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.
Good Saumil. You figured it out.
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
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();
}
}
}
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
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.
please kindly explain how to run this code in eclipse.
Options were Run as ->java applet
->java application
->eclipse app
->osgi app
Hi Shivansh,
You should go for Java application.
All the programs which uses web languages like html, jsp should be run as java application.
if more than one user name and password exists in the database means is this code works ? i thing query got some errors
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.
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.
}
}
Excelent post….. I have a question if I have a sqlserver DB, what is the code in the DBConnection.java ???
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.
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)
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.
Hey JayTai, I was facing similar problem, but it was resolved when I included the mysql.jar file in my netbeans.
Marvelous post….
Thank you very much John.
good job.Will help a lot of people.Thanks for taking the initiative.
Thank you Puja.
where is LoginBean.java source code
I added it now Denny. I missed it before. Thank you for reminding me.
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.
Thank you sampath.
You can ask me if you face any difficulties in understanding the code.
what is the username and password in login page
Hi Hiten,
You can insert any username and password in the database table and try logging in with them.
You can refer to the following video to understand how it is done.
https://youtu.be/_WLeWa7mjHw