Upload image file into database using java servlet, jdbc and mysql

In this example we are going to create a project which will enable users to upload the image into the database.
First of all turn on mysql database connection and open the mysql command line and paste the following sql script and create the new database as well as table.

create database AppDB;

use AppDB;

CREATE TABLE `contacts` (
  `contact_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `photo` mediumblob,
  PRIMARY KEY (`contact_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1


Now, lets create a dynamic web project into the eclipse and design the structure as follows:



Now, let's create the front end using the jsp pages.
uploadImage.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>File Upload</title>
</head>
<body>
    <h1>Upload any image to mysql DB</h1>
    <form method="post" action="fileUpload"
        enctype="multipart/form-data">
        <table>
            <tr>
                <td>First Name:</td>
                <td><input type="text" name="firstName" size="10"
                    required="required" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" name="lastName" size="10"
                    required="required" /></td>
            </tr>
            <tr>
                <td>Choose Image:</td>
                <td><input type="file" name="photo" size="10"
                    required="required" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"></td>
                <td><input type="reset" value="Clear" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


submit.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>Success</title>
</head>
<body>
    <h3><%=request.getAttribute("Message")%></h3>
</body>
</html>


db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/AppDB
user=root
password=password 


DbUtil.java

package com.amzi.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DbUtil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
                Properties prop = new Properties();
                InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
                prop.load(inputStream);
                String driver = prop.getProperty("driver");
                String url = prop.getProperty("url");
                String user = prop.getProperty("user");
                String password = prop.getProperty("password");
                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return connection;
        }

    }
}


UploadServlet.java

package com.amzi.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.amzi.util.DbUtil;

@WebServlet("/fileUpload")
@MultipartConfig(maxFileSize = 16177215) // upload file up to 16MB
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = -1623656324694499109L;
    private Connection conn;

    public UploadServlet() {
        conn = DbUtil.getConnection();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        // gets values of text fields
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");

        InputStream inputStream = null;

        // obtains the upload file part in this multipart request
        Part filePart = request.getPart("photo");
        if (filePart != null) {
            // debug messages
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());

            // obtains input stream of the upload file
            inputStream = filePart.getInputStream();
        }

        String message = null; // message will be sent back to client

        try {
            // constructs SQL statement
            String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, firstName);
            statement.setString(2, lastName);

            if (inputStream != null) {
                // fetches input stream of the upload file for the blob column
                statement.setBlob(3, inputStream);
            }

            // sends the statement to the database server
            int row = statement.executeUpdate();
            if (row > 0) {
                message = "Image is uploaded successfully into the Database";
            }
        } catch (SQLException ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        }
        // sets the message in request scope
        request.setAttribute("Message", message);

        // forwards to the message page
        getServletContext().getRequestDispatcher("/submit.jsp").forward(
                request, response);
    }
}


Now, we are ready to run the project and once we run the project we are able to view the following result.





Click here to download the code.

You may also like...

Check username availability using Java, JSP, AJAX, MySQL, JDBC, Servlet

Login application using jsp servlet and mysql database

JSF login and register application

 

 

Call by value example

Below example will explain how call by value is happening in java.

public class CallByValue {

    private int value = 5;

    private int change(int input) {
        input = input + 10;// changes will be in the local variable only
        return input;
    }

    public static void main(String args[]) {
        CallByValue cv = new CallByValue();

        System.out.println("before change: " + cv.value);
        System.out.println("calling change method directly: " + cv.change(50));
        System.out.println("after change: " + cv.value);
    }
}


Output:

before change: 5
calling change method directly: 60
after change: 5

User definded object in ArrayList - Generics Example

Here, we are going to create a list of user defined object type. First of all we can create a java object with some sample fields and getters and setters methods along with overridden toString method.

User.java

package com.amzi.examples;

public class User {

    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;
    }

    @Override
    public String toString() {
        return "User [userName=" + userName + ", password=" + password + "]";
    }
}


Now, we are going to write a java class which will create a list of this user object and will see various list methods.

ArrayListExample.java

package com.amzi.examples;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample1 {

    public static void main(String[] args) {

        // initializing user object with some sample data
        User user1 = new User();
        user1.setUserName("Amzi");
        user1.setPassword("password1");

        User user2 = new User();
        user2.setUserName("Saiyad");
        user2.setPassword("password2");

        // initializing list object of type User
        List<User> list = new ArrayList<User>();

        // adding user object into the list
        list.add(user1);
        list.add(user2);

        System.out.println("Printing user1 elements: " + user1);

        System.out.println("Printing list object: " + list);

        // looping through the userObject and list
        for (User u : list) {
            System.out.println(u.getUserName() + "\t--  " + u.getPassword());
        }
    }
}


Output:

Printing user1 elements: User [userName=Amzi, password=password1]
Printing list object: [User [userName=Amzi, password=password1], User [userName=Saiyad, password=password2]]
Amzi    --  password1
Saiyad    --  password2

ArrayList example

In this example we are going to see the java ArrayList in action. List is the interface and ArrayList is the implementation of the List interface.

Here, we are going to create a list which will take Integer types and then we are going to iterate them in a loop and print out the result.

package com.amzi.examples;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {

    public static void main(String[] args) {

        // invoke and create the list of 5 Integer objects
        // declaring generics type as Integer so only Integer value can fit in
        // instead of Integer type we can also add String or other Object type
        List<Integer> list = new ArrayList<Integer>(5);
        // calling add method to add the element into the list
        list.add(15);
        list.add(20);
        list.add(25);
        list.add(15);
        list.add(20);
        list.add(15);// duplicate values can be added
        list.add(null);// null also can be added.

        // loop through the list elements
        for (Integer index : list) {
            System.out.println("First List elements: " + index);
        }
        System.out.println("========================");

        // at second position of the existing list, adding new Integer value
        // list index starts from 0
        list.add(2, 22);

        // loop through the list after adding the new element
        for (Integer index : list) {
            System.out.println("Second list elements: " + index);
        }
    }
}


Output:

First List elements: 15
First List elements: 20
First List elements: 25
First List elements: 15
First List elements: 20
First List elements: 15
First List elements: null
========================
Second list elements: 15
Second list elements: 20
Second list elements: 22
Second list elements: 25
Second list elements: 15
Second list elements: 20
Second list elements: 15
Second list elements: null

Convert json to java object using Gson library

I published the last post about how to convert java object into the json format. We are going to reuse some of its code so take a look at the previous post by clicking here

Make sure you have the Gson library installed in your class path, I described that in my previous post.
Lets create a json file with some sample data in it.

testFile.json

{
  "id": 1,
  "name": "Amzi",
  "skills": [
    "Java",
    "JSP",
    "JDBC"
  ]
}


Now, lets create a java class which will read the json file and convert that into the java object.

Json2Java.java

package com.amzi.java;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class Json2Java {
    public static void main(String[] args) {

        Gson gson = new Gson();
        try {
            //read json file from the buffered reader object
            BufferedReader br = new BufferedReader(new FileReader(
                    "c:\\users\\amzi\\desktop\\testFile.json"));

            // convert the json string back to object
            TestObject obj = gson.fromJson(br, TestObject.class);

            System.out.println(obj);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

TestObject [ID = 1, name = Amzi, skills = [Java, JSP, JDBC]]

Convert java object to json format using Gson library

In one of my previous post we have discussed about the same topic but using jackson library. For your reference - click here

In this example we are going to see how to convert java object into the json format using Google's Gson library.

Gson is pretty easy to understand and it has mainly below two methods to note.
  • toJson() – Convert Java object to JSON format
  • fromJson() – Convert JSON into Java object
First of all, in order for us to compile the code we need the Gson library. For maven users please paste the below dependency inside your pom.xml file. Non maven users can download it online and paste it in the project class path.

pom.xml

 <dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>1.7.1</version>
 </dependency>

Now, lets create a java test object with some initialized values. Later on we are going to convert this java object to json format using Gson library.

TestObject.java

import java.util.ArrayList;
import java.util.List;

public class TestObject {
    private int id = 1;     private String name = "Amzi";     private List<String> skills = new ArrayList<String>() {         {             add("Java");             add("JSP");             add("JDBC");         }     };     public int getId() {         return id;     }     public void setId(int id) {         this.id = id;     }     public String getName() {         return name;<     }     public void setName(String name) {         this.name = name;     }     public List<String> getSkills() {         return skills;     }     public void setSkills(List<String> skills) {         this.skills = skills;     }     @Override     public String toString() {         return "TestObject [ID = " + id + ", name = " + name + ", skills = "                 + skills + "]";     } }


Below is the core logic which will enable us to convert the java object to json. We are going to use the toJson() method which is available in Gson object

Java2Json.java

package com.amzi.java;
import java.io.FileWriter; import java.io.IOException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Java2Json {     public static void main(String[] args) {         TestObject obj = new TestObject();         //initialize Gson object         //setPrettyPrinting().create() is for batter formating.         Gson gson = new GsonBuilder().setPrettyPrinting().create();         // convert java object to JSON format,         // and returned as JSON formatted string         String json = gson.toJson(obj);         try {             // write converted json data to a file named "testFile.json"             FileWriter writer = new FileWriter(                     "c:\\users\\amzi\\desktop\\testFile.json");             writer.write(json);             writer.close();         } catch (IOException e) {             e.printStackTrace();         }         System.out.println(json);     } }


Along with the below output into the console we may also check for the newly created testFile.json in the location we mentioned.

Output:

{
  "id": 1,
  "name": "Amzi",
  "skills": [
    "Java",
    "JSP",
    "JDBC"
  ]
}

Convert Json to Java object using Jackson library

I published a post on "how to convert java object into the json format. In case you missed it, click here for your reference. Today, we are going to reverse that, meaning from the json file we are going to read and convert that into the java object.

We have the json file in the local machine user.json

user.json

{"messages":["Your name is - Amzi","Your Id is - 1","Welcome to the world!!!"],"name":"Amzi","id":1}


I'd assume that you already have the required jackson library in your project class path. I described that in my previous post in detail.

Now, lets create the java file which will read json file and create the java object out of it. For that we are going to use the readValue() method which is available in ObjectMapper class. ObjectMapper class is the part of the jackson library.

Json2Java.java

package com.amzi.java;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Json2Java {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            // read from file, convert it to user class
            User user = mapper.readValue(new File(
                    "c:\\Users\\Amzi\\Desktop\\user.json"), User.class);

            // display to console
            System.out.println(user);

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

User [id=1, name=Amzi, messages=[Your name is - Amzi, Your Id is - 1, Welcome to the world!!!]]

Convert java object to Json using jackson library

In this example we are going to learn how to convert java object into the json format.

Lets create a maven project into the eclipse workspace. Open up the pom.xml file and paste the following code inside the project node.

If you are not using maven then you may download the library from the google and add it to the class path.

pom.xml

  <repositories>
    <repository>
        <id>codehaus</id>
        <url>http://repository.codehaus.org/org/codehaus</url>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
  </dependencies>


Lets create the User object first. This is a java object with 2 fields and a list.

User.java

package com.amzi.java;

import java.util.ArrayList;
import java.util.List;

public class User {

    private int id = 01;
    private String name = "Amzi";
    private List<String> messages = new ArrayList<String>();
    {

        messages.add("Your name is - " + name);
        messages.add("Your Id is - " + id);
        messages.add("Welcome to the world!!!");

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public List<String> getMessages() {
        return messages;
    }

    public void setMessages(List<String> messages) {
        this.messages = messages;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", " + "messages="
                + messages + "]";
    }
}


Jackson library provides us the writeValue() method and which is available in ObjectMapper class. In this method we are going to pass the location where we want to save the json file.

Java2Json.java

package com.amzi.java;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Java2Json {
    public static void main(String[] args) {

        User user = new User();
        ObjectMapper mapper = new ObjectMapper();

        try {
            // converts user object to json string, and save to a file
            mapper.writeValue(
                    new File("c:\\Users\\Amzi\\Desktop\\user.json"), user);

            // display to console
            System.out.println(mapper.defaultPrettyPrintingWriter()
                    .writeValueAsString(user));
           
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Now, we are done parsing the java object into the json format. Once we run the above java class, we are going to get following output into the console and also the same output will be saved inside the user.json file.

Output:

{
  "messages" : [ "Your name is - Amzi", "Your Id is - 1", "Welcome to the world!!!" ],
  "name" : "Amzi",
  "id" : 1
}

JavaScript to disable numbers in the text box

Business use case:

Create two text boxes  and put following client side validation to it.
  • Disable numbers to be printed
  • Enable only numbers
Implementation:

We can achieve the above business use case in at least two different ways by using java script on the client side. We can create a jsp or html page for the text box creation and we can call the java script function from there. 

test.jsp

<html>
<head>
<script src="script.js"></script>
</head>
<body>
    <fieldset>
        <legend>First way</legend>
        <table>
            <tr>
                <td>Only number field :</td>
                <td><input type="text" name="number"
                    onkeypress="return onlyNumbers(event)" /></td>
            </tr>

            <tr>
                <td>No digits field :</td>
                <td><input type="text" name="number"
                    onkeypress="return !onlyNumbers(event)" /></td>
            </tr>
        </table>
    </fieldset>
    <fieldset>
        <legend>Second way</legend>
        <table>
            <tr>
                <td>Only number field :</td>
                <td><input type="text" maxlength="10"
                    onkeypress="return validNo(this,event)" /></td>
            </tr>
            <tr>
                <td>No digits field :</td>
                <td><input type="text" maxlength="10"
                    onkeypress="return !validNo(this,event)" /></td>
            </tr>
        </table>
    </fieldset>
</body>
</html>


Now, below java script is the core ingredient of this example. Here, I'm writing two java script functions which essentially do the same thing.

script.js

function validNo(input, kbEvent) {
    var keyCode, keyChar;
    keyCode = kbEvent.keyCode;
    if (window.event)
        keyCode = kbEvent.keyCode;
    else
        keyCode = kbEvent.which;                                    
    if (keyCode == null) return true;
    keyChar = String.fromCharCode(keyCode);
    var charSet = "0123456789";
    if (charSet.indexOf(keyChar) != -1) return true;
    if (keyCode == null || keyCode == 0 || keyCode == 8 || keyCode == 9 || keyCode == 13 || keyCode == 27) return true;
    return false;
}

function onlyNumbers(e) {
    var keynum;
    var keychar;
    var numcheck;

    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;
    return numcheck.test(keychar);
}




Disable right click from the web page.

Below java script will prevent any user from right clicking on the web page. We can include the following script in the head tag of jsp or html page.


Read values from CSV file using BufferedReader and split using StringTokenizer

In my previous post I have explained about the StringTokenizer object. Please click here to review my previous post on StringTokenizer.

In this example we are going to read the input value from the CSV file and split them by a pipe ("|") delimiter and iterate them by using StringTokenizer object.

First of all lets create a csv file and input some test data to it.

test.csv



Now lets create the java class in which we are going to read the csv file by using BufferedReader objec. Then, we are going to use the StringTokenizer object and will specify the delimiter as pipe ("|"). The next step is to iterate the each element that we are getting and displaying them. Please have a look at the below code snippet.

ReadFromFile.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class ReadFromFile {

    public static void main(String[] args) {

        BufferedReader br = null;
        try {
            String line;
            br = new BufferedReader(new FileReader(
                    "c:/Users/Amzi/Desktop/test.csv"));

            while ((line = br.readLine()) != null) {
                System.out.println(line);
                System.out.println("-------------");

                StringTokenizer stringTokenizer = new StringTokenizer(line, "|");
               
                while (stringTokenizer.hasMoreElements()) {

                    Integer id = Integer.parseInt(stringTokenizer.nextElement()
                            .toString());
                    Double balance = Double.parseDouble(stringTokenizer
                            .nextElement().toString());
                    String username = stringTokenizer.nextElement().toString();

                    StringBuilder sb = new StringBuilder();
                    sb.append("\nId : " + id);
                    sb.append("\nBalance : " + balance);
                    sb.append("\nUsername : " + username);
                    sb.append("\n*******************\n");

                    System.out.println(sb);
                }
            }

            System.out.println("Successfully completed");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}


Output

1| 1.11| Amzi
-------------

Id : 1
Balance : 1.11
Username :  Amzi
*******************

2| 3.33| Saiyad
-------------

Id : 2
Balance : 3.33
Username :  Saiyad
*******************

Successfully completed

StringTokenizer in Java

StringTokenizer is a java object which is available in java.util package. Using this object we can split the String into multiple chunks and have it used as per the business use case.

We can split the String by providing any delimiters to it or default delimiter is "space". Let's have a look at the below example.

import java.util.StringTokenizer;

public class StringTokenizerTest {
    public static void main(String[] args) {

        String test = "This is an : example string: we are going : to split it";
        StringTokenizer st1 = new StringTokenizer(test);

        System.out.println("---- Split by space(by default) ------");
        while (st1.hasMoreElements()) {
            System.out.println(st1.nextElement());
        }

        System.out.println("---- Split by colon ':' ------");
        StringTokenizer st2 = new StringTokenizer(test, ":");

        while (st2.hasMoreElements()) {
            System.out.println(st2.nextElement());
        }
    }
}


Output:

---- Split by space(by default) ------
This
is
an
:
example
string:
we
are
going
:
to
split
it
---- Split by colon ':' ------
This is an
 example string
 we are going
 to split it

Redirect request from servlet using sendRedirect method

In this example we are going to understand the method sendRedirect which is available in HttpServletResponse object. This method will take a String value as an input parameter. Essentially this String can be Servlet, jsp or html page. Checkout the example below for batter understanding.

Create a dynamic web project in your Eclipse IDE. Under src folder create two java servlets as defined below.

DemoServlet.java

package com.java.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/Demo")//This is url pattern for this servlet
//Servlet 3.0 doesn't require to be mapped in web.xml
public class DemoServlet extends HttpServlet {

    private static final long serialVersionUID = -4111596859324406153L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
       
        System.out.println("Inside DemoServlet doGet method");
        //Calling servlet which has the name testing
        res.sendRedirect("testing");
    }
}


TestingServlet.java

package com.java.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/testing")//This is url pattern for this servlet
public class TestingServlet extends HttpServlet {

    private static final long serialVersionUID = -4111596859324406153L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        System.out.println("Inside TestingServlet doGet method");
        res.sendRedirect("http://www.google.com");
        //or this can be any jsp or html page created under WebContent folder
        //res.sendRedirect("index.jsp");
    }
}


We don't need web.xml configuration as we are using servlet 3.0. So, once you done coding you can go ahead and deploy the project on the server and hit the below url on your browser.

http://localhost:8080/HelloWorld/Demo

As soon as we hit the url first of all the Demo servlet is going to be invoked. Now, Demo servlet is calling the testing servlet using sendRedirect method in it. Therefore, testing servlet is going to be invoked in next step. Again this servlet also has sendRedirect method in it and that is calling the google homepage so, finally the page is going to be redirected to the google home page.
Note: In the end result the browser url is going to be changed to the google url.

Servlet JSP based login example

Here, we are gonna build a login screen which will take the hardcoded username and password value from servlet.

Before we proceed make sure you have following software up and running.
  1. Eclipse IDE
  2. Tomcat server
First of all, create the dynamic web project on your Eclipse IDE and under WebContent folder create a new jsp file and name it login.jsp

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 Page</title>
</head>
<body>
    <form action="TestServlet" method="post">
        <fieldset>
            <legend>User login</legend>
            <table>
                <tr>
                    <td>User Name:</td>
                    <td><input type="text" name="user" /></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input type="password" name="pass" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" /></td>
                </tr>
            </table>
        </fieldset>
    </form>
</body>
</html>


Upon successful login we are going to redirect the page to the success page. So, lets create the success page.

success.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>Success Page</title>
</head>
<body>
    <h1 align="center">Welcome to the world of servlets!</h1>
    <h3 align="center" style="color: blue">Created by Amzi...</h3>
</body>
</html>


Now, lets create a servlet which will handle the client request. For this particular example only the doPost method is required however, I am writing doGet, init and destroy method as well just for the sake of batter understanding of the example. Under the src folder lets create the new servlet.

TestServlet.java

package com.java.amzi;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String redirect = "test.jsp";
    private static final String success = "success.jsp";

    public TestServlet() {
        super();
        System.out.println("Inside the constructor of the servlet");
    }

    public void init(ServletConfig config) throws ServletException {
        System.out.println("In the init method!");
    }

    public void destroy() {
        System.out.println("The destroy method is called!");
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("Inside the doGet method");
        String user = request.getParameter("user");
        System.out.println(user);
        String pass = request.getParameter("pass");
        
        if (user.equals("Admin") && pass.equalsIgnoreCase("passw0rd"))
            response.sendRedirect(success);
        else {
            System.out.println("inside the else part");
            response.sendRedirect(redirect);
        }
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Inside the doPost method");
        doGet(request, response);
    }
}


That is all required to run this example so, now go ahead and deploy the project on your tomcat server and the screen will look as per below sceenshot.



Enter the correct username and password

Now have a look at the console.


Related Post:

Login application using jsp servlet and mysql database 

JSF login and register application

 

How to connect to Oracle database from java code - JDBC

In this example we are going to connect to the Oracle database.

Pre-requisite:

  1. We need Oracle database up and running.
  2. Oracle JDBC driver
  3. Eclipse IDE (Recommended but not required)
Download oracle jdbc driver from here

If you are working on IDE then create a java project and add the oracle jdbc driver to the build path. And your project structure should look something like this



Now, we are going to write the core logic in order to connect to the oracle database.

package com.amzi.database;

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

public class ConnectOracle {

    public static void main(String[] amzi) {
       
        System.out.println("-------- Oracle JDBC Connection Testing ------");
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Oracle JDBC Driver not found!!!");
            e.printStackTrace();
            return;
        }

        System.out.println("Oracle JDBC Driver Registered!");
        Connection connection = null;
        try {
            connection = DriverManager
                    .getConnection(
                            "jdbc:oracle:thin:@localhost:1521:xe",
                            "yourUsername", "yourPassword");
        } catch (SQLException e) {
            System.out.println("Connection Failed!!!");
            e.printStackTrace();
            return;

        }

        if (connection != null) {
            System.out.println("Connection established successfully!");
        } else {
            System.out.println("Connection is null!");
        }
    }
}


If everything goes fine, you should see your console as below.

-------- Oracle JDBC Connection Testing ------
Oracle JDBC Driver Registered!
Connection established successfully!

Check username availability using Java, JSP, AJAX, MySQL, JDBC, Servlet


Hey guys, today we are gonna be developing the username availability application based on the real world scenario and using the technologies which are used across almost all the major IT firms.

Before we begin writing the code I'd assume that you guys have following software installed.

  1. Eclipse IDE
  2. Tomcat app server
  3. MySQL Database


Alright, first of all we are going to start the DB and will create the database and the table. After that we can enter some test values. Check the script below.
MySQL Script:
create database students;

create table users(
 uid int primary key 
        auto_increment,
 uname varchar(20) unique
 );

INSERT INTO `students`.`users` 
(`uid`, `uname`) VALUES ('1', 
'Amjad');INSERT INTO 
`students`.`users` (`uid`, 
`uname`) VALUES ('2', 'Amzi');


Create a dynamic web project in your IDE workspace and the project structure should look something like this.

Next are going to create the view using jsp, the view will consist of a simple text box which will check if the input string value is 3 character long or not. If yes then it will go ahead and make a query and will check the availability of the username.

index.jsp


Username Availability


 


 
 


Now, we are going to write a servlet which will create a database connection and make a query to it.
CheckAvailability.java
package com.amzi.servlets;

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class CheckAvailability extends HttpServlet {

 private static final long serialVersionUID = -734503860925086969L;

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String connectionURL = "jdbc:mysql://localhost:3306/students"; // students is my database name
            Connection connection = null;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, "root", "password");
            String uname = request.getParameter("uname");
            PreparedStatement ps = connection.prepareStatement("select uname from users where uname=?");
            ps.setString(1,uname);
            ResultSet rs = ps.executeQuery();
             
            if (!rs.next()) {
                out.println(""+uname+" is avaliable");
            }
            else{
            out.println(""+uname+" is already in use");
            }
            out.println();

        } catch (Exception ex) {
            out.println("Error ->" + ex.getMessage());
        } finally {
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}


Also, we can configure the deployment descriptor as follows.
web.xml


    
        check
        com.amzi.servlets.CheckAvailability
    
    
        check
        /check
    
    
        
            30
        
    
    
        index.jsp
        
    


Note: In addition to these code we also need jquery library and mysql connector jar file. Just in case you are unable to find those, you may click here to get the complete source code.

Now, we are all set to deploy and test the code on the server. We can hit the below url
http://localhost:8080/UserAvailability/
And, the page will look something like this

Understanding Java Recursion...Factorial Example

In one line if someone wanted to explain,
"Recursion is, the method that call itself". Easy enough ehy...

If the input number is 0 or 1, we are returning 1 else we are going to compute the result as
n! = n * (n-1)!
A simple mathematics formula.

Here I am going to create the static method so, I don't have to create an instance of the method and can call just with the method name.

Note:
Here the datatype that I'm using is int so, ofcourse it may have some limitations and hence you can't go beyond certain limit however you guys may go ahead and have it double, long etc.

Let's have a look at the way we can code for any factorials using Java Recursion concept.

public class RecursionExample {

 private static int factorial(int input) {
  int fact = 0;
  if (input <= 1)
   fact = 1;
  else
   fact = input * factorial(input - 1);

  return fact;
 }

 public static void main(String[] args) {
  System.out.println(factorial(5));
 }
}
The above example will print out 120 as an output.

Create and write content into CSV file / Spread-sheet

Below example will illustrate how to create a csv or excel file and write any desired content into it. In this example we are going to use the FileWriter object and which is available in java.io package.

package com.amzi.xml;

import java.io.FileWriter;
import java.io.IOException;

public class CreateCsvFile {
 private static void generateCsvFile(String fileName) {
  FileWriter writer = null;
  try {
   writer = new FileWriter(fileName);
   writer.append("Name");
   writer.append(',');
   writer.append("ID");
   writer.append('\n');

   writer.append("Amzi");
   writer.append(',');
   writer.append("001");
   writer.append('\n');

   writer.append("Bond");
   writer.append(',');
   writer.append("007");
   writer.append('\n');

   System.out.println("CSV file is created...");

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    writer.flush();
    writer.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 public static void main(String[] args) {
  String location = "/users/Amzi/test.csv";
  generateCsvFile(location);
 }
}

Validate phone number using java regular expression

In this example we are going to be validating any phone number. We are going to put following checks against any phone number under test.

  • The phone number should be 10 digit number.
  • Splitted by hi-fen(-) and the end result should look like xxx-xxx-xxxx

package com.amzi.xml;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePhoneNumber {
 public static void main(String[] args) {

  String phNumber = "123-222-3333";
  //String phNumber = "123 123 1234";

  Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
  Matcher matcher = pattern.matcher(phNumber);

  if (matcher.matches()) {
   System.out.println("Phone Number is Valid");
  } else {
   System.out
   .println("Phone Number isn't in this formate XXX-XXX-XXXX");
  }
 }
}

Output
Phone Number is Valid

How to get any webpage/URL content and save it on local drive using java code.

Alright, so today we are going to be coding to get the snapshot of any website. Here, we are using two jdk inbuilt packages java.io and java.net
This code is pretty self explanatory however, wherever required I've added the comments.
package com.amzi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GetWebpageContent {
 public static void main(String[] args) {

  URL url;

  try {
   // enter any url to get its content
   url = new URL("http://www.javaandj2eetutor.blogspot.com");
   URLConnection conn = url.openConnection();

   // open the stream and put it into BufferedReader
   BufferedReader br = new BufferedReader(new InputStreamReader(
     conn.getInputStream()));
   String inputLine;

   // save it anywhere in local machine for offline use
   String fileName = "/users/Amzi/test.html";
   File file = new File(fileName);
   if (!file.exists()) {
    file.createNewFile();
   }

   FileWriter fw = new FileWriter(file.getAbsoluteFile());
   BufferedWriter bw = new BufferedWriter(fw);

   while ((inputLine = br.readLine()) != null) {
    bw.write(inputLine);
   }

   bw.close();
   br.close();

   System.out.println("Your file is saved in " + fileName
     + " location.");

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

Once we run the above program, if everything goes fine then the URL content supposed to be saved in the location we specified in the program and in the console weare supposed to see something like this.
Your file is saved in /users/Amzi/test.html location.

JAXB example for Unmarshalling – Convert XML content into a Java Object.

First of all, let's get started with the java DTO with some fields and annotations we will complete the object.

package com.java.example;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

    private String firstName;
    private String lastName;
    private long ssn;
    private int eId;

    @XmlElement
    public String getFirstName() {
        return firstName;
    }

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

    @XmlElement
    public String getLastName() {
        return lastName;
    }

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

    @XmlElement
    public long getSsn() {
        return ssn;
    }

    public void setSsn(long ssn) {
        this.ssn = ssn;
    }

    @XmlAttribute
    public int geteId() {
        return eId;
    }

    public void seteId(int eId) {
        this.eId = eId;
    }

    @Override
    public String toString() {
        return "Employee [firstName=" + firstName + ", lastName=" + lastName
                + ", ssn=" + ssn + ", eId=" + eId + "]";
    }
   
}


You can copy the employee.xml file to your C:\Temp\employee.xml and your file should look something like this.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee eId="7">
    <firstName>James</firstName>
    <lastName>Bond</lastName>
    <ssn>123456789</ssn>
</employee>


Now, let's write the core logic which will convert the xml into the java object. In new file object I've mentioned the location for the employee.xml file. Make sure you have the file at the same location with same content otherwise you may have to change the coding.

package com.java.example;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XmlToJava {

    public static void main(String[] args) {
        try {
            File file = new File("C:\\Temp\\employee.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);
            System.out.println(employee);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


Once after we run XmlToJava class we are going to get the following output into the console.

Employee [firstName=James, lastName=Bond, ssn=123456789, eId=7]

Java code for school grade book

Here, I am going to write java code which will do following:
  • Will print the number of students along with their score.
  • The entire class average.
  • Lowest grade in the class.
  • Highest grade in the class.
So, let's get it started with the first java class.

public class GradeBook {
    private String courseName;
    private int[] grades;

    public GradeBook(String name, int[] gradesArray) {
        courseName = name;
        grades = gradesArray;
    }

    public void setCourseName(String name) {
        courseName = name;
    }

    public String getCourseName() {
        return courseName;
    }

    public void displayMessage() {
        System.out.printf("Welcome to the grade book for\n%s!\n\n",
                getCourseName());
    }

    public void processGrades() {
        outputGrades();
        System.out.printf("\nClass average is %.2f\n", getAverage());
        System.out.printf("Lowest grade is %d\nHighest grade is %d\n\n",
                getMinimum(), getMaximum());
        outputBarChart();
    }

    public int getMinimum() {
        int lowGrade = grades[0];
        for (int grade : grades) {
            if (grade < lowGrade)
                lowGrade = grade;
        }
        return lowGrade;
    }

    public int getMaximum() {
        int highGrade = grades[0];
        for (int grade : grades) {
            if (grade > highGrade)
                highGrade = grade;
        }
        return highGrade;
    }

    public double getAverage() {
        int total = 0;
        for (int grade : grades)
            total += grade;
        return (double) total / grades.length;
    }

    public void outputBarChart() {
        System.out.println("Grade distribution: ");
        int[] frequency = new int[11];
        for (int grade : grades)
            ++frequency[grade / 10];
        for (int count = 0; count < frequency.length; count++) {
            if (count == 10)
                System.out.printf("%5d: ", 100);
            else
                System.out.printf("%02d-%02d: ", count * 10, count * 10 + 9);
            for (int stars = 0; stars < frequency[count]; stars++)
                System.out.print("*");
            System.out.println();
        }
    }

    public void outputGrades() {
        System.out.println("The grades are:\n");
        for (int student = 0; student < grades.length; student++)
            System.out.printf("Student %2d: %3d\n", student + 1,
                    grades[student]);
    }
}


Now, let's create the other java class which will enable us to test the above class and methods

public class GradeBookTest {

    public static void main(String[] args) {

        // array of student grades. This is the data that we will use to
        // populate the array.
        // There are many ways of obtaining data to populate arrays, and some of
        // those ways are by user-input,
        // or by reading from a file, or in this case, we provide the data using
        // an array initializer list.
        int[] gradesArray = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };

        GradeBook myGradeBook = new GradeBook("Java Programming", gradesArray);

        myGradeBook.displayMessage();
        myGradeBook.processGrades();
    }
}


Output:

Welcome to the grade book for
Java Programming!

The grades are:

Student  1:  87
Student  2:  68
Student  3:  94
Student  4: 100
Student  5:  83
Student  6:  78
Student  7:  85
Student  8:  91
Student  9:  76
Student 10:  87

Class average is 84.90
Lowest grade is 68
Highest grade is 100

Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
  100: *

How to read and manipulate values from text file by using java code

First of all create a text file and call it "txtFile.txt", now add the following values into the text file.

10
50.1
Amzi

Now, create a java class into the same folder where you have stored the txtFile.txt
The java class will be as follows.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ManipulateTxtfile {

    public static void main(String[] args) {
        try {
            Scanner in = new Scanner(
                    new File("txtFile.txt"));
            int first = in.nextInt();
            double second = in.nextDouble();
            String name = in.next();
            double sum = first + second;
            System.out.println("Hello " + name + "\nThe sum of " + first
                    + " and " + second + " is = " + sum);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}


The output of the above program will look something like this:

Hello Amzi
The sum of 10 and 50.1 is = 60.1

Run some task periodically using core java concepts

In this example we are going to write a java program which will run every 2 seconds and will perform some task for us. In our example we are simply going to print the new date time stamp after every two seconds but in a real world there could be plenty of scenarios one can think of. One example could be updating the user interface after every few seconds and fetch the latest data from the database.

The code is pretty self explanatory, by looking at the embedded comments it will be even easier. 

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Amzi
 */
public class Scheduler extends TimerTask {

    Date currentTime;

    // Add your core logic/business use case
    public void run() {
        currentTime = new Date();
        System.out.println("The current Time is :" + currentTime);
    }

    public static void main(String args[]) throws InterruptedException {

        Timer timer = new Timer(); // Step 1 - Instantiate Timer Object
        Scheduler sc = new Scheduler(); // Step 2 - Instantiate the class
        timer.schedule(sc, 0, 2000); // Step 3 - Create task for every 2 seconds
        // Using the for loop along with the System.exit to terminate the
        // program otherwise it will keep on running
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread..." + i);
            // Make thread sleep for 2 seconds
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("We are getting out of here...");
                System.exit(0);
            }
        }
    }
}


The above code will print the following output into the console.

Execution in Main Thread...0
The current Time is :Mon Nov 25 14:33:07 EST 2013
Execution in Main Thread...1
The current Time is :Mon Nov 25 14:33:09 EST 2013
Execution in Main Thread...2
The current Time is :Mon Nov 25 14:33:11 EST 2013
Execution in Main Thread...3
The current Time is :Mon Nov 25 14:33:13 EST 2013
Execution in Main Thread...4
The current Time is :Mon Nov 25 14:33:15 EST 2013
The current Time is :Mon Nov 25 14:33:17 EST 2013
Execution in Main Thread...5
We are getting out of here...
The current Time is :Mon Nov 25 14:33:19 EST 2013