Login Application using jsp, servlet,jdbc and Maven

In this article we are going to create a simple web login application using JSP, servlet,maven and mysql database.In this tutorial, Servlet and jsp is used to create a simple login web application to run on the Tomcat server. It also demonstrates how Maven brings in the relevant dependent JAR files like servlet jar and mysql related jars.


Tools used :

In order to create an application we are going to use the following tools.

  • JDK 1.6
  • Servlet 2.5
  • Eclipse
  • Tomcat 6.0
  • MySql 5.5

In this article we are going to create a simple web login application using JSP, servlet,maven and mysql database.In this tutorial, Servlet and jsp is used to create a simple login web application to run on the Tomcat server. It also demonstrates how Maven brings in the relevant dependent JAR files like servlet jar and mysql related jars.


Tools used :

In order to create an application we are going to use the following tools.

  • JDK 1.6
  • Servlet 2.5
  • Eclipse
  • Tomcat 6.0
  • MySql 5.5





Step 1 : Create Web Application Project using Maven Template

Create a Java web application project from “maven-archetype-webapp” template.

mvn archetype:generate -DgroupId=com.javawebtutor -DartifactId=LoginWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

maven java project

Step 2 : Eclipse IDE integration

Convert this project to Eclipse web project with Maven command “mvn eclipse:eclipse -Dwtpversion=1.5".Open command prompt and navigate to generated "LoginWebApp" project and issue following command.

mvn eclipse:eclipse -Dwtpversion=1.5

Step 3 : Import the Project into eclipse

Import the project into eclipse IDE. Directory structure of projects is given bellow.

maven web project

Step 4 : Update pom.xml file

Add the Servlet and mysql dependencies in pom.xml.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javawebtutor</groupId>
	<artifactId>LoginWebApp</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>LoginWebApp Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>LoginWebApp</finalName>
	</build>
</project>

After updating the pom.xml again execute "mvn eclipse:eclipse -Dwtpversion=1.5". After executing this command Maven will download required libraries.



Step 5 : Create java directory :

Create a directory named java under main."/src/main".

Note:-If created java directory is not in class path of project,we need to add this directory to class path of your project.

Step 6 : Add java directory to classpath of the Project :

  • Right click on Project -> Build Path -> Configure build path.a new screen will open in that screen click on Source tab and then click on Add folder as shown bellow.

  • maven web project

  • Again one new screen will open and in that screen select the java checkbox and click on ok again OK as shown bellow.

  • maven web project

    Now Java folder is in classpath of project.

    Step 6 : Create Database Table in mysql

    CREATE TABLE `USER` (
      `id` int(10) unsigned NOT NULL auto_increment,
      `first_name` varchar(45) NOT NULL,
      `last_name` varchar(45) NOT NULL,
      `email` varchar(45) NOT NULL,
      `username` varchar(45) NOT NULL,
      `password` varchar(45) NOT NULL,
      `regdate` date NOT NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    Step 7 : Create jsp files

    Create jsp files inside webapp directory of project.

    index.jsp
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Example</title>
        </head>
        <body bgcolor="silver">
            <form method="post" action="login.jsp">
                <center>
                <table border="0" width="30%" cellpadding="3">
                    <thead>
                        <tr>
                            <th colspan="2">Login Page</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Username</td>
                            <td><input type="text" name="userName" value="" /></td>
                        </tr>
                        <tr>
                            <td>Password</td>
                            <td><input type="password" name="password" value="" /></td>
                        </tr>
                        <tr>
                            <td><input type="submit" value="Login" /></td>
                            <td><input type="reset" value="Reset" /></td>
                        </tr>
                        <tr>
                            <td colspan="2">New User <a href="register.jsp">Register Here</a></td>
                        </tr>
                    </tbody>
                </table>
                </center>
            </form>
        </body>
    </html>
    
    register.jsp
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Registration</title>
        </head>
        <body bgcolor="silver">
            <form method="post" action="userRegistration.jsp">
                <center>
                <table border="1" width="30%" cellpadding="5">
                    <thead>
                        <tr>
                            <th colspan="2">Enter Information Here</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>First Name</td>
                            <td><input type="text" name="firstName" value="" /></td>
                        </tr>
                        <tr>
                            <td>Last Name</td>
                            <td><input type="text" name="lastName" value="" /></td>
                        </tr>
                        <tr>
                            <td>Email</td>
                            <td><input type="text" name="email" value="" /></td>
                        </tr>
                        <tr>
                            <td>User Name</td>
                            <td><input type="text" name="userName" value="" /></td>
                        </tr>
                        <tr>
                            <td>Password</td>
                            <td><input type="password" name="password" value="" /></td>
                        </tr>
                        <tr>
                            <td><input type="submit" value="Submit" /></td>
                            <td><input type="reset" value="Reset" /></td>
                        </tr>
                        <tr>
                            <td colspan="2">Already registered!! <a href="index.jsp">Login Here</a></td>
                        </tr>
                    </tbody>
                </table>
                </center>
            </form>
        </body>
    </html>
    
    userRegistration.jsp
    <%@ page import="java.sql.*"%>
    <%
        String userName = request.getParameter("userName");    
        String password = request.getParameter("password");
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String email = request.getParameter("email");
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jwt",
                "root", "mukesh");
        Statement st = con.createStatement();
        int i = st.executeUpdate("insert into USER(first_name, last_name, email, username, password, regdate) values ('" + firstName + "','" 
        + lastName + "','" + email + "','" + userName + "','" + password + "', CURDATE())");
        if (i > 0) {
            response.sendRedirect("welcome.jsp");
           
        } else {
            response.sendRedirect("index.jsp");
        }
    %>
    
    login.jsp
    <%@ page import="java.sql.*"%>
    <%
        String userName = request.getParameter("uname");    
        String password = request.getParameter("password");
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jwt",
                "root", "mukesh");
        Statement st = con.createStatement();
        ResultSet rs;
        rs = st.executeQuery("select * from user where userName='" + userName + "' and password='" +password + "'");
        if (rs.next()) {
            session.setAttribute("userid", userName);
            response.sendRedirect("success.jsp");
        } else {
            out.println("Invalid password <a href='index.jsp'>try again</a>");
        }
    %>
    
    success.jsp
    <%
        if ((session.getAttribute("userName") == null) || (session.getAttribute("userName") == "")) {
    %>
    You are not logged in<br/>
    <a href="index.jsp">Please Login</a>
    <%} else {
    %>
    Welcome <%=session.getAttribute("userid")%>
    <a href='logout.jsp'>Log out</a>
    <%
        }
    %>
    
    welcome.jsp
    Registration is Successful.
    Please Login Here <a href='index.jsp'>Go to Login</a>
    
    logout.jsp
    <%
    session.setAttribute("userName", null);
    session.invalidate();
    response.sendRedirect("index.jsp");
    %>
    

    Final Structure Of Project

    Final structure of project is given bellow:

    maven web project

    Step 8 : Build the project

    Open command prompt and navigate to "LoginWebApp" project and issue mvn:package command.

    mvn package
    

    After executing above command "LoginWebApp.war" file will generate in target folder of the project.

    Step 9 : Run it

    Copy the generated "LoginWebApp.war" file from target folder to your tomcat webapp folder and start the server. After successful start of server open web browser and enter http://localhost:8080/LoginWebApp/index.jsp in URL bar we will see following output.

    maven web project

    maven web project

    You can download the source code of the example by clicking on the Download link below.

    Source (Developed in Eclipse) : Download




comments powered by Disqus