How to enable/disable button/dropdown using DOM/JavaScript.

One of the most and highly used DOM component is - "document".
In this example we are going to cover how to use the DOM object and we are going to disable/enable the HTML button and dropdown.
Let's write the sample HTML code which has the button and the dropdown element.

disableButton.html

<html>
   <head>
      <script src = "test.js"></script>
   </head>
   <body style="background-color:#F2F2F2;">
      <button id="btn01">OK</button>
      <button onclick="disableElement()">Disable</button>
      <button onclick="enableElement()">Enable</button>
      
      <select id="mySelect">
         <option>Java</option>
         <option>.Net</option>
         <option>PHP</option>
         <option>JavaScript</option>
      </select>
      
      <input type="button" onclick="disable()" value="Disable list" />
      <input type="button" onclick="enable()" value="Enable list" />
   </body>
</html>

Now that we are done with the sample HTML, let's write the JavaScript functions which will enable and disable the button and dropdown element.

test.js

function disableElement() {
    document.getElementById("btn01").value = "Disabled";
    document.getElementById("btn01").disabled = true;
}

function enableElement() {
    document.getElementById("btn01").value = "OK";
    document.getElementById("btn01").disabled = false;
}

function disable() {
    document.getElementById("mySelect").disabled = true;
}

function enable() {
    document.getElementById("mySelect").disabled = false;
}
 
The browser will render the above code something like this.
 

 

How to Confirm the password field using the JavaScript

In this example we are going to write a JavaScript code to make sure that the user is entering the password and confirm password fields equal to each other. First of all, we are going to design the UI using the standard html file.

myTest.html


    
    


    


myTest.js
function validate() {
    var password1 = document.getElementById("pass1");
    var password2 = document.getElementById("pass2");
    var msg = document.getElementById("message");
    var greenColor = "#66cc66";
    var redColor = "#ff6666";

    if (password1.value == password2.value) {
        password2.style.backgroundColor = greenColor;
        msg.style.color = greenColor;
        msg.innerHTML = "Password is Matched!";
        return true;
    } else {
        password2.style.backgroundColor = redColor;
        msg.style.color = redColor;
        msg.innerHTML = "Password do not match! Please try again.";
        return false;
    }
}


tutorial.css
  .tutorialWrapper{
      width: 100%;
    }
    .tutorialWrapper form{
      background-color: #A9E2F3;
      border: 1px solid #cc9;
      padding: 10px;
      font-family: verdana;
      width: 75%;
      font-size: 1em;
    }
    .fieldWrapper{
      margin: 2px 0 2px 0;
      padding: 0;
    }
    .tutorialWrapper label{
      float: left;
      text-align: right;
      margin: 0 5px 0 0;
      width: 30%;
    }
    .tutorialWrapper input{
      width: 200px;
      border: 1px solid #cc9;
    }
    .confirmMessage{
      margin: 0;
      padding: 0;
      font-size: .8em;
    }

Output

When Password and Confirm Password fields are equal then we will get the following result.


Until both the fields are not equal to each other it will keep displaying the below result.

 

HashMap Example

Map is an Interface and which is available in java.util package and HashMap is an implementation of the Map interface. HashMap stores the data in key/value pair.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapExample {

    public static void main(String[] args) {

        Map<Object, Object> map = new HashMap<Object, Object>();
        // put the key and values in String format
        map.put("1", "Java");
        map.put("2", "Programming in C");
        map.put("AI", "Lisp");
        map.put("Script", "JavaScript");

        System.out.println("Before Change - " + map.get("1"));
        System.out.println("Key \t Value");
        System.out.println("----------------");

        // loop through the map data using Iterator Interface
        Iterator<?> iterator = map.entrySet().iterator();
        Map.Entry<String, String> entry = null;
        while (iterator.hasNext()) {
            entry = (Entry<String, String>) iterator.next();
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        }

        // Let's change the value for the key 1 and key 2
        map.put("1", "OOP");
        map.put("2", "Procedural");
        System.out.println("After Change - " + map.get("1"));
        System.out.println("After Change - " + map.get("2"));
    }
}


Output:


Java Program to show money change in dollars, quarters etc

In this example we are going to look at the java program which will enable us to enter the money received by the customer and will populate the remaining amount to be given to the customer.

import java.util.Scanner;

public class MakeChange {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int price;
        int provided;
        int change;
        System.out.print("Enter the purchase price:");
        price = (int) Math.round(keyboard.nextDouble() * 100);
        System.out.print("Enter the amount given by the customer:");
        provided = (int) Math.round(keyboard.nextDouble() * 100);
       
        if (provided > price) {
            System.out.println("The change is: " + ((provided - price)/100.00));
            System.out.println("The customer should be given the change as follows:");
            change = provided - price;
            // Since you multiplied by 100 you have to divide by 2000 to get the
            // number of twenties for change.
            int twenties = change / 2000;
           
            if (twenties > 0) { // if the change is less than $20 this will be a 0
                change = change % 2000; // this resets the value of change to
                // the remainder after the twenties are
                // calculated but only if there was at
                // least enough to make one twenty
                System.out.println(twenties + " $20 bill(s)");
            }
           
            int tens = change / 1000;
            if (tens > 0) {
                change = change % 1000;
                System.out.println(tens + " $10 bill(s)");
            }
           
            int fives = change / 500;
            if (fives > 0) {
                change = change % 500;
                System.out.println(fives + " $5 bill(S)");
            }
           
            int ones = change / 100;
            if (ones > 0) {
                change = change % 100;
                System.out.println(ones + " $1 bill(s)");
            }
           
            int quarters = change / 25;
            if (quarters > 0) {
                change = change % 25;
                System.out.println(quarters + " quarter coin(s)");
            }
           
            int dimes = change / 10;
            if (dimes > 0) {
                change = change % 10;
                System.out.println(dimes + " dime coin(s)");
            }
           
            int nickels = change / 5;
            if (nickels > 0) {
                change = change % 5;
                System.out.println(nickels + " nickel coin(s)");
            }
            int pennies = change;
            System.out.println(pennies + " penny coin(s)");
        }
        if (provided < price) { // this statement is saying that if the customer
            // doesn't pay enough, it will tell the user
            System.out.print("Not enough money!");
        } else if (provided == price) { // this statement says if the amount
            // provided matches the price, then
            // there is no change necessary
            System.out.print("No change is necessary!");
        }
    }
}


Output:




Java Diamond Pattern

In one of my previous post we have printed the Pyramid pattern. In this short tutorial we are going to print the Diamond pattern using java for loop.


public class StarDiamond {

    public static void main(String[] args) {

        int num = 5;
        for (int i = 1; i <= num; i++) {
            for (int j = num; j >= i; j--) {
                System.out.print(" ");
            }
            for (int m = 1; m <= i; m++) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }
        for (int i = 1; i <= num; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(" ");
            }
            for (int m = num; m >= i; m--) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }
    }
}


Output:




You may also like:

Pyramid Pattern







JSF login and register application

In this example we are going to create a login and signup application using JSF framework. I am planning to use the below technologies to create the whole application.

  1. Eclipse IDE
  2. Tomcat server
  3. JSF framework
  4. Mysql Database
Before you proceed, make sure you have above software up and running. Also, we need to have some of the dependency jar files in order to compile and run the project. I am going to include the complete source code including the jsf and mysql jar files at the end of this tutorial. You can also go ahead and download it from online resources.


Now, open up the eclipse IDE and create the dynamic web project and set the project structure as below.

Project Structure



Lets design the database table and schema. You can turn on your mysql connection and copy the below db script into your mysql client.

Mysql DB script:

CREATE TABLE `user` (
 `firstname` varchar(15) NOT NULL,
 `password` varchar(15) DEFAULT NULL,
 `lastname` varchar(15) DEFAULT NULL,
 `email` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`firstname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, lets create the context.xml file under META-INF folder. This file will hold the database connection information and also we can configure the datasource into this file.

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/database" auth="Container" type="javax.sql.DataSource"
        username="root" password="password" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/appdb" />
</Context>


Now, we are going to create the front end using some xhtml files.

index.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<f:loadBundle basename="resources.application" var="msg" />

<h:head>
<title><h:outputText value="#{msg.welcomeTitle}" /></title>
</h:head>

<h:body>
    <h3>
        <h:outputText value="#{msg.welcomeHeading}" />
    </h3>
    <p>
        <h:outputText value="#{msg.welcomeMessage}" />
    </p>
</h:body>
</h:html>


error.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Error</title>
</h:head>
<h:body>
    <f:view>
        <p>
            <b>Sorry, either name or password is incorrect please try again</b>
        </p>
        <p>
            <h:outputLink value="login.xhtml">Login Again</h:outputLink>
        </p>
    </f:view>
</h:body>
</html>


home.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Home Page</title>
</h:head>
<h:body>
    <h:panelGrid id="panel" columns="2" border="1" cellpadding="10"
        cellspacing="1">
        <f:facet name="header">
            <h:outputText value="Welcome to the Java and J2EE Tutor" />
        </f:facet>
        <h:outputLabel value="Already a user" />
        <h:outputLink value="login.xhtml">Sign In</h:outputLink>
        <h:outputLabel value="Not a member yet" />
        <h:outputLink value="register.xhtml">Sign Up</h:outputLink>
        <f:facet name="footer">
            <h:panelGroup style="display:block; text-align:center">
                <h:outputLabel value="Created by Amzi" />
            </h:panelGroup>
        </f:facet>
    </h:panelGrid>
</h:body>
</html>


login.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Login Page</title>
</h:head>
<h:body>
    <f:view>
        <h:form id="loginForm">
            <table frame="box">
                <tr>
                    <th>Login Page</th>
                </tr>
                <tr>
                    <td><h:outputText value="Enter Your Name : " /></td>
                    <td><h:inputText id="inputName" value="#{user.firstName}"
                            required="true" requiredMessage="Name field must not be empty" />
                    </td>
                    <td><h:message for="inputName" style="color:red" /></td>
                </tr>
                <tr>
                    <td><h:outputText value="Enter password :" /></td>
                    <td><h:inputSecret id="inputPassword" value="#{user.password}"
                            required="true"
                            requiredMessage="Password field must not be empty" /></td>
                    <td><h:message for="inputPassword" style="color:red" /></td>
                </tr>
                <tr>
                    <td><h:commandButton value="Sign In" action="#{user.login}" /></td>
                    <td><h:outputText value="Not a User " /> 
                        <h:outputLink value="register.xhtml">Sign Up</h:outputLink>
                    </td>
                </tr>
            </table>
        </h:form>
    </f:view>
</h:body>
</html>


register.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Registration Page</title>
</h:head>
<h:body>
    <f:view>
        <h:form id="registerForm">
            <table>
                <tr>
                    <td><h:outputText value="Enter Your First Name:" /></td>
                    <td><h:inputText id="fname" value="#{user.firstName}"
                            required="true" requiredMessage="Please enter your first name" /></td>
                    <td><h:message for="fname" style="color:red" /></td>
                </tr>
                <tr>
                    <td><h:outputText value="Enter Your Last Name:" /></td>
                    <td><h:inputText id="lname" value="#{user.lastName}"
                            required="true" requiredMessage="Please enter your last name" /></td>
                    <td><h:message for="lname" style="color:red" /></td>
                </tr>
                <tr>
                    <td><h:outputText value="Enter Your email ID:" /></td>
                    <td><h:inputText id="email" value="#{user.email}"
                            required="true" requiredMessage="Please enter your email id" /></td>
                    <td><h:message for="email" style="color:red" /></td>
                </tr>
                <tr>
                    <td><h:outputText value="Enter Password :" /></td>
                    <td><h:inputSecret id="psw" value="#{user.password}"
                            required="true" requiredMessage="Please enter your password" /></td>
                    <td><h:message for="psw" style="color:red" /></td>
                </tr>
                <tr>
                    <td />
                    <td><h:commandButton value="Register" action="#{user.add}" /></td>
                </tr>
                <tr>
                    <td><h:outputLink value="home.xhtml">Home</h:outputLink></td>
                </tr>
            </table>
        </h:form>
    </f:view>
</h:body>
</html>


success.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Success Page</title>
</h:head>
<h:body>
    <f:view>
        <p>Successfully logged in</p>
        <p>Hi, #{user.firstName}</p>
        <h:form>
            <p>
                <h:commandLink value="logout" action="#{user.logout}" />
            </p>
        </h:form>
    </f:view>
</h:body>
</html>


unsuccess.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<h:head>
    <title>Unsuccess Page</title>
</h:head>
<h:body>
    <f:view>
        <p>There is an error in signing up. See Server Console for error.</p>
        <h:outputLink value="register.xhtml">Back</h:outputLink>
    </f:view>
</h:body>
</html>


Now, the frontend is almost completed so, lets create a java class which will have some of the required fields and methods which will enable us to insert the data into the database and validate the data for the login functionality.

User.java

package com.amzi.beans;

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

@ManagedBean(name = "user")
@RequestScoped
public class User {

    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String dbPassword;
    private String dbName;
    DataSource ds;

    public User() {
        try {
            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/jdbc/database");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public String getDbPassword() {
        return dbPassword;
    }

    public String getDbName() {
        return dbName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String name) {
        this.firstName = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String add() {
        int i = 0;
        if (firstName != null) {
            PreparedStatement ps = null;
            Connection con = null;
            try {
                if (ds != null) {
                    con = ds.getConnection();
                    if (con != null) {
                        String sql = "INSERT INTO user(firstname, password, lastname, email) VALUES(?,?,?,?)";
                        ps = con.prepareStatement(sql);
                        ps.setString(1, firstName);
                        ps.setString(2, password);
                        ps.setString(3, lastName);
                        ps.setString(4, email);
                        i = ps.executeUpdate();
                        System.out.println("Data Added Successfully");
                    }
                }
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                try {
                    con.close();
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (i > 0) {
            return "success";
        } else
            return "unsuccess";
    }

    public void dbData(String uName) {
        if (uName != null) {
            PreparedStatement ps = null;
            Connection con = null;
            ResultSet rs = null;

            if (ds != null) {
                try {
                    con = ds.getConnection();
                    if (con != null) {
                        String sql = "select firstname,password from user where firstname = '"
                                + uName + "'";
                        ps = con.prepareStatement(sql);
                        rs = ps.executeQuery();
                        rs.next();
                        dbName = rs.getString("firstname");
                        dbPassword = rs.getString("password");
                    }
                } catch (SQLException sqle) {
                    sqle.printStackTrace();
                }
            }
        }
    }

    public String login() {
        dbData(firstName);
        if (firstName.equals(dbName) && password.equals(dbPassword)) {
            return "output";
        } else
            return "invalid";
    }

    public void logout() {
        FacesContext.getCurrentInstance().getExternalContext()
                .invalidateSession();
        FacesContext.getCurrentInstance()
                .getApplication().getNavigationHandler()
                .handleNavigation(FacesContext.getCurrentInstance(), null, "/login.xhtml");
    }
}


In the resources folder we can create the application.properties file just for the demonstration purposes.

application.properties

# -- welcome --
welcomeTitle=JSF Application

welcomeHeading=Welcome to my Blog!

welcomeMessage=This is a JSF application. You can find the application.properties file with this message in the src/resources folder.


Now, since this is JSF based application so, we are creating faces-config.xml file. This xml file will contain the navigation rule, message bundle configuration etc.

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
    <application>
        <message-bundle>resources.application</message-bundle>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
    </application>
    <navigation-rule>
        <description>login user</description>
        <from-view-id>/login.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{user.login}</from-action>
            <from-outcome>output</from-outcome>
            <to-view-id>/success.xhtml</to-view-id>
        </navigation-case>

        <navigation-case>
            <from-action>#{user.login}</from-action>
            <from-outcome>invalid</from-outcome>
            <to-view-id>/error.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

    <navigation-rule>
        <description>register new user</description>
        <from-view-id>/register.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{user.add}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/success.xhtml</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{user.add}</from-action>
            <from-outcome>unsuccess</from-outcome>
            <to-view-id>/unsuccess.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>


And, finally we are going to create the web.xml file

web.xml

<?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_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>jsfLoginExample</display-name>
    <welcome-file-list>
        <welcome-file>/home.xhtml</welcome-file>
    </welcome-file-list>
    <resource-ref>
        <description>Login Database</description>
        <res-ref-name>jdbc/database</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
        <url-pattern>*.jsf</url-pattern>
        <url-pattern>*.xhtml</url-pattern>
        <url-pattern>*.jsp</url-pattern>
    </servlet-mapping>
    <context-param>
        <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>resources.application</param-value>
    </context-param>
    <listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
</web-app>


Now, we are all set to deploy our application onto the tomcat server. And, once we deploy our project the application should redirect to home.xhtml

So, first of all lets check to see if the the sign up link is working correctly.




Clicking on logout link will redirect the page to the login page.


Now, we are going to register with the duplicate primary key and see what happens.





 Also, we can verify the index page by hitting this URL


Download the complete source code.


JSF example - hello world

In this example we are going to write a simple hello world application based on JSF 2.0 (Java Server Faces)

Here we are going to use the following technologies.

  1. Maven
  2. JSF
  3. Tomcat
  4. Eclipse
Lets create the project structure into your eclipse workspace as per the below screen shot.


 Maven Script 

     <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.el</groupId>
            <artifactId>el-ri</artifactId>
            <version>1.0</version>
        </dependency>
    </dependencies>


HelloBean.java
package com.amzi.example;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import java.io.Serializable;

@ManagedBean(name="hello")
@SessionScoped
public class HelloBean implements Serializable {

 private static final long serialVersionUID = 1L;

 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}


hello.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">
 
    <h:head>
        <title>JSF 2 Example</title>
    </h:head>
    <h:body>
     <h3>JSF 2 Example</h3>
     <h:form>
        <h:inputText value="#{hello.name}"></h:inputText>
        <h:commandButton value="Submit" action="welcome"></h:commandButton>
     </h:form>
    </h:body>
</html>


welcome.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"    
      xmlns:h="http://java.sun.com/jsf/html">
 
    <h:head>
     <title>JSF 2 Example</title>
    </h:head>
    <h:body>
     <h3>JSF 2 Example</h3>
     <h3>Welcome #{hello.name}</h3>
    </h:body>
</html>

web.xml
<?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>JavaServerFaces</display-name>
 
 <!-- Change to "Production" when you are ready to deploy -->
 <context-param>
  <param-name>javax.faces.PROJECT_STAGE</param-name>
  <param-value>Development</param-value>
 </context-param>
 
 <!-- Welcome page -->
 <welcome-file-list>
  <welcome-file>faces/hello.xhtml</welcome-file>
 </welcome-file-list>
 
 <!-- JSF mapping -->
 <servlet>
  <servlet-name>Faces Servlet</servlet-name>
  <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <!-- Map these files with JSF -->
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>*.jsf</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>*.faces</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>*.xhtml</url-pattern>
 </servlet-mapping>
 
</web-app>


Now, lets deploy the project on the tomcat server and the result will look something like this



Download Source Code

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