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