Login application using jsp servlet and mysql database

Today we are going to create a simple web login application using JSP, servlet and mysql database. In order to create an application we are going to use the following software.

  1. MySql database
  2. Eclipse IDE
  3. Tomcat server
Firstly, lets create a database and a table in mysql. Turn on the database connection and open the mysql command prompt and paste the below code.

create database form;

use form;

CREATE  TABLE `form`.`login` (
  `user` VARCHAR(20) NOT NULL ,
  `password` VARCHAR(20) NOT NULL ,
  PRIMARY KEY (`user`) ); 
INSERT INTO `form`.`login` (`user`, `password`) VALUES ('Admin', 'passw0rd');

Now, open up the Eclipse IDE and create a dynamic web project and create the project structure as per the screen shot below.



Lets create the front end with two basic jsp pages.

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
    <form action="loginServlet" method="post">
        <fieldset style="width: 300px">
            <legend> Login to App </legend>
            <table>
                <tr>
                    <td>User ID</td>
                    <td><input type="text" name="username" required="required" /></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="userpass" required="required" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" /></td>
                </tr>
            </table>
        </fieldset>
    </form>
</body>
</html>


welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
    <h3>Login successful!!!</h3>
    <h4>
        Hello,
        <%=session.getAttribute("name")%></h4>
</body>
</html>


Now, lets create the login DAO which will enable us to connect our login application with mysql database and execute the query to the DB.

LoginDao.java
package com.amzi.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginDao {
    public static boolean validate(String name, String pass) {        
        boolean status = false;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "form";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "password";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager
                    .getConnection(url + dbName, userName, password);

            pst = conn
                    .prepareStatement("select * from login where user=? and password=?");
            pst.setString(1, name);
            pst.setString(2, pass);

            rs = pst.executeQuery();
            status = rs.next();

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return status;
    }
}


Now, we are going to create the servlet which will capture the input parameter from the jsp and validate it against the LoginDao.

LoginServlet.java
package com.amzi.servlets;

import java.io.IOException;
import java.io.PrintWriter;

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;

import com.amzi.dao.LoginDao;

public class LoginServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

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

        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
        
        String n=request.getParameter("username");  
        String p=request.getParameter("userpass"); 
        
        HttpSession session = request.getSession(false);
        if(session!=null)
        session.setAttribute("name", n);

        if(LoginDao.validate(n, p)){  
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");  
            rd.forward(request,response);  
        }  
        else{  
            out.print("<p style=\"color:red\">Sorry username or password error</p>");  
            RequestDispatcher rd=request.getRequestDispatcher("index.jsp");  
            rd.include(request,response);  
        }  

        out.close();  
    }  
} 


Finally, lets configure the web.xml file for servlet and welcome file configuration.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    version="2.5">
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.amzi.servlets.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


That's all it takes to create a simple web login application. This is not the ideal login application as it needs lot of modification such as security etc. Anyways, for now let's run the project on the tomcat server and test the application.



Now, let's input the invalid data and check the result.



Now, I am using the correct credentials which will match with the database result and redirect the page to the welcome file.

Note: The URL is internally redirecting the page to the welcome.jsp file since we are using the forward method. If instead we would have used redirect method, in that case we can see the request URL in the browser.


Download Code

77 comments:

  1. Thanks , it helped me a lot. this is a very good example.--Roy

    ReplyDelete
    Replies
    1. when i am using the correct credentials i am getting

      java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

      can you tell me what is the problem.

      Delete
    2. I resolve the problem in the mysql server where you run the following query - - **** GRANT ALL PRIVILEGES ON * * TO 'your_User_database' @ '%'.
      IDENTIFIED BY 'some_pass' WITH GRANT OPTION; **** With that I could enter from the APP I hope you work.

      Delete
    3. change database name ,username and password for your configuration

      Delete
    4. Enter this "mysqld -u root -p" on cmd.

      Delete
    5. Enter 'mysql -u root -p ' and enter password to access first.

      Delete
    6. You can just simply check your database name This is the error for Invalid Database Name:)

      Delete
    7. You can just simply check your database name This is the error for Invalid Database Name:)

      Delete
  2. when i am using the correct credentials i am getting

    java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

    can you tell me what is the problem.

    ReplyDelete
    Replies
    1. We are also facing the same issue.Can anyone please help us to resolve this issue.thanks in advance.

      Delete
    2. Everything works fine, except I when logging in as Admin and passw0rd. it says 'its incorrect' how can i know that it is connected to mysql

      Delete
    3. u just have to import your oracle jdbc library

      Delete
  3. Hi iam new to J2EE i run this project n im able to see the index.jsp i.e login page but what are the valid credentials to see the success page im not getting that


    thanks in advancce

    ReplyDelete
    Replies
    1. Credentials should be Admin and passw0rd. Have a look at the very first step that I've mentioned about the DB script.

      Delete
    2. yes i have entered the the same credentials which u mentioned above but it shows me "Sorry username or password error" and in the console "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver" do i need to configure MySQL with the eclipse if so could you please detail me the steps for the same .....Thanks

      Delete
    3. Download and extract the mysql driver from this link (http://dev.mysql.com/downloads/connector/j/) if you don't have it already. Once done, add that to your eclipse project class path.

      Delete
    4. Thank you...... now i can run the project without any errors it helped me a lot :)

      Delete
  4. hey bro can u create the same example for oracle..thanks in advance ..i tried but m getting this error..


    HTTP Status 500 - File "/index.jsp" not found

    type Exception report

    message File "/index.jsp" not found

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

    exception

    javax.servlet.ServletException: File "/index.jsp" not found
    org.apache.jasper.servlet.JspServlet.handleMissingResource(JspServlet.java:425)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:392)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    com.amzi.servlets.LoginServlet.doPost(LoginServlet.java:39)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    note The full stack trace of the root cause is available in the Apache Tomcat/8.0.5 logs.

    ReplyDelete
  5. welcome page open nahi ho rha hai login krne ke baad ....the request resources is not available..

    ReplyDelete
  6. correct user id or password input krne pr bhi login nahi ho rha hai.......sir kya welcome.jsp ki mapping nahi hogi kya?

    ReplyDelete
    Replies
    1. Control would be redirected to the welcome page if the validate() method goes successful. Check the LoginServlet class. Please post your stacktrace here and I'll have a look at it.

      Delete
  7. sir i facing some problem when i attach my code here .problem is that "Your HTML cannot be accepted:Tag is not allowed:P".help me how i attached my code here

    ReplyDelete
    Replies
    1. This wouldn't help me, I need to see the console logs, anyways if the HTML tag is not allowed in your servlet then probably you may try removing the tag and just use the String value only. I don't see any possible reason why it shouldn't allow the HTML tag withing your servlet.

      Delete
  8. Sir,
    when i am using the correct credentials i am getting

    java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

    can you tell me what is the problem?

    ReplyDelete
  9. sir,
    i have add the jar file in build path but this error is coming............
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    plz help

    ReplyDelete
  10. Thank you so much for this basic neat app, I was able to revise my basic concepts by running this perfectly.

    ReplyDelete
  11. Thanks you so much for app. it is very..................good

    ReplyDelete
  12. javax.servlet.ServletException: Error instantiating servlet class com.amzi.servlets.LoginServlet
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)


    root cause

    java.lang.ClassNotFoundException: com.amzi.servlets.LoginServlet
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

    ReplyDelete
    Replies
    1. hi i am also getting the same error can u please help me how did u resolve this exception

      Delete
  13. please help me for final year project

    ReplyDelete
  14. hi i am new web apllication I am getting the following error while compiling LoginServlet.java
    LoginServlet.java:30: cannot find symbol
    symbol : variable LoginDao
    location: class LoginServlet
    if(LoginDao.validate(n, p)){
    ^
    1 error

    ReplyDelete
    Replies
    1. You need to create LoginDao class to resolve this error.

      Delete
  15. This comment has been removed by the author.

    ReplyDelete
  16. Very good explanation.........................thanks

    ReplyDelete
  17. Sir ,can you help me please ?
    i got this problem
    java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist :(

    ReplyDelete
    Replies
    1. Hi please check if your DB and table are created.

      Delete
    2. Hey,
      yes of course !
      and there is no vue named in the same way as the table i wanna use .

      Delete
  18. hi,
    Its Showing error message its not taking any input,
    m using oracle 10g,


    ReplyDelete
  19. Anyway its directly ..executing else part...
    m not using any primary key in table...i took simple table....

    ReplyDelete
  20. Clear and neat explanation! Good job!

    ReplyDelete
  21. sir i have problem in getting output its showing like this

    HTTP Status 404 - /vd/servlet/vd.LogOut

    --------------------------------------------------------------------------------

    type Status report

    message /vd/servlet/vd.LogOut

    description The requested resource is not available.


    --------------------------------------------------------------------------------

    Apache Tomcat/7.0.64


    what should i do how to reolve this problem

    ReplyDelete
  22. please share me the solution as soon as poaaible

    ReplyDelete
  23. Access denied for user 'root'@'localhost' (using password: YES)

    error :-(

    ReplyDelete
    Replies
    1. String password = "password"; enter your mysql root password

      Delete
  24. HTTP Status 404 - /Login1/loginServlet error

    ReplyDelete
  25. Nice Explanation.
    http://gpcomptech.blogspot.in/2013/09/creating-simple-login-form-using-eclipse.html

    ReplyDelete
  26. hi, I am giving correct login credential still getting "HTTP Status 404 - Servlet login is not available" error on login button click.

    ReplyDelete
  27. i want to go Home page after successfully register, what should do?
    thanks in advance for your kind ans.

    ReplyDelete
  28. if(p.equals("passw0rd")){
    RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
    rd.forward(request,response); }
    validate method is not working but equals method working............why??

    ReplyDelete
    Replies
    1. On the LoginServlet.java, chage de if condition:
      if(LoginDao.validate(n, p))
      to
      if(LoginDao.validate(n, p) == true)

      Delete
  29. On the LoginServlet.java, chage de if condition:
    if(LoginDao.validate(n, p))
    to
    if(LoginDao.validate(n, p) == true)

    ReplyDelete
  30. Modules:
    SignInProject (/SignInProject)

    2016-12-03 13:51:34.274:INFO::main: Logging initialized @624ms
    2016-12-03 13:51:34.461:INFO:oejs.Server:main: jetty-9.2.13.v20150730
    2016-12-03 13:51:34.912:INFO:oejw.StandardDescriptorProcessor:main: NO JSP Support for /SignInProject, did not find org.eclipse.jetty.jsp.JettyJspServlet
    2016-12-03 13:51:35.018:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@3796751b{/SignInProject,file:/E:/java/loginform/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/SignInProject/,AVAILABLE}{E:/java/loginform/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/SignInProject}
    2016-12-03 13:51:35.126:INFO:oejs.ServerConnector:main: Started ServerConnector@1810399e{HTTP/1.1}{0.0.0.0:8080}
    2016-12-03 13:51:35.126:INFO:oejs.Server:main: Started @1490ms
    2016-12-03 13:51:36.210:INFO:/SignInProject:qtp1128032093-19: No JSP support. Check that JSP jars are in lib/jsp and that the JSP option has been specified to start.jar

    ReplyDelete
  31. plz......... giv me jar related issues

    ReplyDelete
  32. sir im getting error as com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: can not load connection class because of underlying exception:'java.lang.NumberFormatException: for input string : "3306form"

    ReplyDelete
  33. plz give direction to resolve this problem

    ReplyDelete
  34. 404 after entering credentials. what could i be doing wrong?

    ReplyDelete
  35. exception

    javax.servlet.ServletException: Wrapper cannot find servlet class com.amzi.servlets.LoginServlet or a class it depends on

    root cause

    java.lang.ClassNotFoundException: com.amzi.servlets.LoginServlet

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  36. On this line "HttpSession session = request.getSession(false);" is there a reason why it is set to false and not true.

    ReplyDelete
  37. Thanks man It's helpme a lot

    ReplyDelete
  38. Please help me, sir!! I just follow steps but I got HTTP Status 404 - /Login1/loginServlet error

    ReplyDelete
  39. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing morejava training in chennai | java training institutes in chennai | java j2ee training institutes in velachery

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
  40. perfect explanation about java programming .its very useful.thanks for your valuable information. best java training in chennai | best java training in velachery

    ReplyDelete
  41. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.java training in chennai | java training institutes in chennai

    ReplyDelete

  42. very useful info, and please keep updating........

    ReplyDelete
  43. I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.
    android development course fees in chennai | android app development training in chennai

    ReplyDelete
  44. Thank you, it seriously helped a lot for my minor project. (y)

    ReplyDelete
  45. It only shows that Sorry username or password error and I cannot enter the welcome page. There is no any other error. Please help

    ReplyDelete
  46. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India.
    or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete
  47. Hello, how to solve this problem.

    May 22, 2018 12:06:44 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files (x86)/Java/jre7/bin/client;C:/Program Files (x86)/Java/jre7/bin;C:/Program Files (x86)/Java/jre7/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Users\SYIKIN\AppData\Local\Microsoft\WindowsApps;;C:\Users\SYIKIN\Pictures\New folder\software\eclipse-jee-luna-R-win32\eclipse;;.
    May 22, 2018 12:06:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:PizzaOrdering' did not find a matching property.
    May 22, 2018 12:06:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:LoginModule' did not find a matching property.
    May 22, 2018 12:06:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:TestProject' did not find a matching property.
    May 22, 2018 12:06:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SignInProject' did not find a matching property.
    May 22, 2018 12:06:44 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["http-bio-8085"]
    May 22, 2018 12:06:44 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler ["ajp-bio-8019"]
    May 22, 2018 12:06:44 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 396 ms
    May 22, 2018 12:06:44 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    May 22, 2018 12:06:44 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.56
    May 22, 2018 12:06:45 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-8085"]
    May 22, 2018 12:06:45 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8019"]
    May 22, 2018 12:06:45 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 664 ms
    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    Last packet sent to the server was 0 ms ago.
    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    Last packet sent to the server was 0 ms ago.
    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    Last packet sent to the server was 0 ms ago.
    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    Last packet sent to the server was 0 ms ago.
    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    Last packet sent to the server was 0 ms ago.

    Thank You. :)

    ReplyDelete