This is the continuation of Export QR Code to PDF in Java. In this article I am going to explain how to add QR Code images to PDF table cells with Sample Example Program.

Libraries we need 

Libraries needed for QR Code generation
  1. zxing-core-1.7.jar
  2. zxing-j2se-1.7.jar
Libraries needed for PDF generation
  1. itextpdf-5.5.0

Create PDF document 

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();

Create Table

// a table with two columns
PdfPTable table = new PdfPTable(2);
// add table to pdf document
document.add(table);

Create Table Cell

// create paragraph
Paragraph para = new Paragraph();
// create pdf cell
PdfPCell cell = new PdfPCell(para);
table.addCell(cell);

Add Image to PDF Cell

// get image instance
Image img = Image.getInstance(RESOURCE);
PdfPCell cell = new PdfPCell();
// add image to pdf cell
cell.addElement(img);

Convert BufferedImage to Image

We will get QR code image in BufferedImage format. We have to convert that into Image format and then we can add that to table cell
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage bi = createQRCode("srinivas", "UTF-8",40, 40);
ImageIO.write(bi, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
Image image = Image.getInstance(imageInByte);

QRCodeFirstTable.java 

Execute this file, You can see generated QR Codes in PDF Table

package sample;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.qrcode.WriterException;

public class QRCodeFirstTable {

    /** The resulting PDF file. */
    public static final String RESULT = "C:/students.pdf";
    // color codes
        private static final int BLACK = 0xFF000000;
        private static final int WHITE = 0xFFFFFFFF;
     /**
     * Main method.
     * 
     * @param args
     *            no arguments needed
     * @throws DocumentException
     * @throws IOException
     * @throws com.google.zxing.WriterException 
     * @throws WriterException 
     */
    public static void main(String[] args) throws IOException,
            DocumentException, WriterException, com.google.zxing.WriterException {
        new QRCodeFirstTable().createPdf(RESULT);
    }

    /**
     * Creates a PDF with information about the movies
     * 
     * @param filename
     *            the name of the PDF file that will be created.
     * @throws DocumentException
     * @throws IOException
     * @throws com.google.zxing.WriterException 
     * @throws WriterException 
     */
    public void createPdf(String filename) throws IOException,
            DocumentException, WriterException, com.google.zxing.WriterException {
        File f=new File(filename);
        if(!f.exists()) {
            f.createNewFile();
        }
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        document.add(createMainTable());
        document.close();
        System.out.println("File was successfully saved ----- " + new File(filename).getAbsolutePath());
    }

    /**
     * Creates our first table
     * 
     * @return our first table
     * @throws IOException
     * @throws MalformedURLException
     * @throws BadElementException
     * @throws com.google.zxing.WriterException 
     * @throws WriterException 
     */
    public static PdfPTable createSubTable(boolean align_left)
            throws BadElementException, MalformedURLException, IOException, WriterException, com.google.zxing.WriterException {
        BaseColor bc = new BaseColor(150, 150, 150);
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        // the cell object
        PdfPCell cell, cell1, cell2;
        Font font = new Font();
        font.setColor(BaseColor.WHITE);
        Chunk c = new Chunk("Srinivas", font);
        Paragraph head = new Paragraph(c);
        head.setFont(font);
        cell = new PdfPCell(head);
        cell.setColspan(2);
        cell.setBackgroundColor(bc);
        cell.setPadding(5f);
        table.addCell(cell);
        Image img = getQRCodeImage("Srinivas", "UTF-8", 50, 50);

        font = new Font();
        font.setSize(10f);
        c = new Chunk("\nSrinivas \n\nSodhanaLibrary \n\nIndia", font);
        Paragraph body = new Paragraph(c);
        cell1 = new PdfPCell(body);
        cell1.setBorderWidthRight(0);
        cell1.setPadding(10f);

        cell2 = new PdfPCell();
        cell2.addElement(img);
        cell2.setBorderWidthLeft(0);
        cell2.setPadding(10f);

        // now we add a cell
        table.addCell(cell1);
        table.addCell(cell2);
        System.out.println("Sub Table was created");
        return table;
    }

    public static PdfPTable createMainTable() throws BadElementException,
            MalformedURLException, IOException, WriterException, com.google.zxing.WriterException {
        // a table with two columns
        PdfPTable table = new PdfPTable(2);
        System.out.println("Main Table was created");
        for (int i = 0; i < 30; i++) {
            // cell object
            PdfPCell cell1 = new PdfPCell();
            cell1.setBorderWidth(0);
            cell1.setPadding(10f);
            cell1.addElement(createSubTable(false));
            table.addCell(cell1);
        }
        return table;
    }

    /**
     * To Generate QR Code Image from text
     * 
     * @param qrCodeData
     *            - text for QR Code image
     * @param charset
     * @param qrCodeheight
     *            - QR Code image height
     * @param qrCodewidth
     *            - QR Code image width
     * @return
     * @throws WriterException
     * @throws IOException
     * @throws com.google.zxing.WriterException
     */
    public static BufferedImage createQRCode(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException, com.google.zxing.WriterException {
        // Generate BitMatrix
        com.google.zxing.common.BitMatrix matrix = new MultiFormatWriter()
                .encode(new String(qrCodeData.getBytes(charset), charset),
                        BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // Converting BitMatrix to Buffered Image
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        System.out.println("qr code image was generated for "+qrCodeData );
        return image;
    }

    public static Image getQRCodeImage(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException, com.google.zxing.WriterException, BadElementException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedImage bi = createQRCode("srinivas", "UTF-8",40, 40);
        ImageIO.write(bi, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        Image image = Image.getInstance(imageInByte);
        System.out.println("Image was generated for qr code image");
        return image;
    }

}
Read More
This article was inspired by Google Login Form UI. This below UI is simple and it displays Login, Register and Forgot-Password panel in on same screen.

Form Structure

<form class="panel" id='login' action='' method='post'>
    ..........
</form>
<form class="panel" id='forgotpassword' action='' method='post'>
    ..........
</form>
<form class="panel" id='register' action='' method='post'>
    .........
</form>

Switch Panel Triggers 

<a class="switchPanelButton" panelclass="panel" panelid="forgotpassword" href="#"> Forgot password </a>

jQuery Code to Switch Panels 

$(".switchPanelButton").click(function(event){
    event.preventDefault();
    var panel = $(this).attr('panelclass');
    $("."+panel).hide();
    var panelid = $(this).attr('panelid');
    $("#"+panelid).show();
});
Read More
QR code is getting famous because of its easy readable nature. You can take snapshot and get the data from it. Now its time to generate PDF file with full QR codes.

Libraries we need 

Libraries needed for QR Code generation
  1. zxing-core-1.7.jar
  2. zxing-j2se-1.7.jar
Libraries needed for PDF generation
  1. itextpdf-5.5.0

Code to generate QR code

    /**
     * To Generate QR Code Image from text
     * @param qrCodeData - text for QR Code image
     * @param charset 
     * @param qrCodeheight - QR Code image height
     * @param qrCodewidth - QR Code image width
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static BufferedImage createQRCode(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException {
        // Generate BitMatrix
        BitMatrix matrix = new MultiFormatWriter().encode(
                new String(qrCodeData.getBytes(charset), charset),
                BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // Converting BitMatrix to Buffered Image 
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

Code to generate PDF file

Document document = new Document();
        
// Get file
PdfWriter.getInstance(document, new FileOutputStream("qrcode.pdf"));
document.open();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
// Get QR code for "Hello"
BufferedImage bi = createQRCode("Hello","UTF-8", 200, 200);
ImageIO.write(bi, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
Image image = Image.getInstance(imageInByte);

// Add image to PDF document
document.add(image);
document.close();

Java class for Exporting QR Codes to PDF files



import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ExporToPDF {
    // color codes
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static void main(String[] args) throws WriterException, IOException,
            NotFoundException {
        
        String charset = "UTF-8"; // or "ISO-8859-1"
        Document document = new Document();
        String filePath="qrcode.pdf";
        try {
            
            // Get file
            PdfWriter.getInstance(document, new FileOutputStream("qrcode.pdf"));
            document.open();
            
            // data to covert to QR code
            String[] qrdata = {"srinivas","dasari","blog.sodhanalibrary.com","pojo.sodhanalibrary.com","flaticon.sodhanalibrary.com","google","facebook","reddit","blogger","yourname"};
            float x = 100f, y = 830f, posx, posy;
            int n=0;
            for (int j = 0; j < 5; j++) {
                posy = y - j * 200f;
                for (int i = 0; i < 2; i++) {
                    posx = x + i * 200f;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    
                    // Get QR code
                    BufferedImage bi = createQRCode(qrdata[n], charset, 200, 200);
                    ImageIO.write(bi, "png", baos);
                    baos.flush();
                    byte[] imageInByte = baos.toByteArray();
                    baos.close();
                    Image image = Image.getInstance(imageInByte);
                    image.setAbsolutePosition(posx, posy);
                    
                    // Add image to PDF document
                    document.add(image);
                    n++;
                }
            }
            document.close();
            System.out.println(new File(filePath).getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * To Generate QR Code Image from text
     * @param qrCodeData - text for QR Code image
     * @param charset 
     * @param qrCodeheight - QR Code image height
     * @param qrCodewidth - QR Code image width
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static BufferedImage createQRCode(String qrCodeData, String charset,
            int qrCodeheight, int qrCodewidth) throws WriterException,
            IOException {
        
        // Generate BitMatrix
        BitMatrix matrix = new MultiFormatWriter().encode(
                new String(qrCodeData.getBytes(charset), charset),
                BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        
        // Converting BitMatrix to Buffered Image 
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
    
}

Read More
By using Hours and Minutes rotation animation keyframes we can create Clock Loader.

Markup

<div class="panel">
    <div class="b-loader"></div>
</div>

CSS3

.panel {
  background:#2fc7f7;
  position:relative;
}

.b-loader {
  width: 84px;
  height: 84px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  position: absolute;
  z-index: 60;
  top: 50px;
  left: 50%;
  margin-left: -44px;
}


.b-loader:before,
.b-loader:after {
  content: ' ';
  background: url(/img/loader-arrow.png) 50% 50% no-repeat;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}


.b-loader:before {
  -o-animation: fxRotateMinute 500ms linear infinite;
  -moz-animation: fxRotateMinute 500ms linear infinite;
  -webkit-animation: fxRotateMinute 500ms linear infinite;
  -webkit-animation: fxRotateMinute 500ms linear infinite;
}

.b-loader:after {
  -o-animation: fxRotateHour 3000ms linear infinite;
  -moz-animation: fxRotateHour 3000ms linear infinite;
  -webkit-animation: fxRotateHour 3000ms linear infinite;
  -webkit-animation: fxRotateHour 3000ms linear infinite;
}

@-o-keyframes fxRotateMinute {
  from {
    -o-transform: rotate(0);
  }
  to {
    -o-transform: rotate(1turn);
  }
}
@-moz-keyframes fxRotateMinute {
  from {
    -moz-transform: rotate(0);
  }
  to {
    -moz-transform: rotate(1turn);
  }
}
@-webkit-keyframes fxRotateMinute {
  from {
    -webkit-transform: rotate(0);
  }
  to {
    -webkit-transform: rotate(1turn);
  }
}
@-webkit-keyframes fxRotateMinute {
  from {
    -webkit-transform: rotate(0);
  }
  to {
    -webkit-transform: rotate(1turn);
  }
}

@-o-keyframes fxRotateHour {
  from {
    -o-transform: rotate(0.25turn);
  }
  to {
    -o-transform: rotate(1.25turn);
  }
}
@-moz-keyframes fxRotateHour {
  from {
    -moz-transform: rotate(0.25turn);
  }
  to {
    -moz-transform: rotate(1.25turn);
  }
}
@-webkit-keyframes fxRotateHour {
  from {
    -webkit-transform: rotate(0.25turn);
  }
  to {
    -webkit-transform: rotate(1.25turn);
  }
}
@-webkit-keyframes fxRotateHour {
  from {
    -webkit-transform: rotate(0.25turn);
  }
  to {
    -webkit-transform: rotate(1.25turn);
  }
}
Read More
We can design menu button in an interactive way like displaying different shapes with animation . Observe the below diagram for shapes with user actions.

HTML Markup 

<div class="side-nav">
  <button class="navbar-toggle">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar top"></span>
    <span class="icon-bar middle"></span>
    <span class="icon-bar bottom"></span>
  </button>
  <div class="menuPanel">
  </div>
</div>

CSS 

.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    margin: -1px;
    padding: 0;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    border: 0
}

.navbar-toggle {
    position: relative;
    float: right;
    margin-right: 15px;
    padding: 9px 10px;
    margin-top: 23px;
    margin-bottom: 23px;
    border: 1px solid transparent;
    border-radius: 1px;
    cursor:pointer;
    z-index:1;
}

.navbar-toggle:focus {
    outline: none
}

.navbar-toggle .icon-bar {
    display: block;
    width: 22px;
    height: 2px;
    border-radius: 1px
}

.navbar-toggle .icon-bar+.icon-bar {
    margin-top: 4px
}

.navbar-toggle {
    display: block;
    background: #2fc7f7;
    float: none;
    width: 75px;
    height: 75px;
    border-radius: 0;
    margin-right: 15px;
    padding: 10px 15px;
    margin-top: 8px;
    margin-bottom: 8px
}

.navbar-toggle:hover {
    -webkit-transition: margin-bottom 500ms ease-in-out;
    transition: margin-bottom 500ms ease-in-out
}

.navbar-toggle:hover span.icon-bar {
    position: relative
}

.navbar-toggle:hover span.icon-bar.top {
    top: 7.5px;
    -webkit-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg)
}

.navbar-toggle:hover span.icon-bar.middle {
    left: 0px;
    position: relative
}

.navbar-toggle:hover span.icon-bar.bottom {
    bottom: 7.5px;
    position: relative;
    -webkit-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    transform: rotate(-90deg)
}

.navbar-toggle span.icon-bar {
    background: #fff;
    display: block;
    width: 40px;
    height: 4px;
    border-radius: 1px;
    -webkit-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transition: all 300ms ease-in-out;
    transition: all 300ms ease-in-out
}

.navbar-toggle.active {
    -webkit-transition: all 300ms ease-in-out;
    transition: all 300ms ease-in-out
}

.navbar-toggle.active span.icon-bar {
    position: relative;
    -webkit-transition: all 300ms ease-in-out;
    transition: all 300ms ease-in-out
}

.navbar-toggle.active span.icon-bar.top {
    -webkit-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
    top: 0px
}

.navbar-toggle.active span.icon-bar.middle {
    width: 0;
    height: 0;
    margin: 0 auto
}

.navbar-toggle.active span.icon-bar.bottom {
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
    margin: 0;
    top: -4px;
}
.menuPanel {
    background: #2fc7f7;
    font-size:40px;
    padding:60px 40px 40px 80px;
    display:none;
    position:absolute;
    top:0px;
    color:#fff;
    line-height:60px;
}

.side-nav {
    position:relative;
    margin:auto;
    width:500px;
}

.side-nav a{
    color:#fff;
    text-decoration:none;
}

jQuery Code

$(function(){
    $(".navbar-toggle").click(function(){
        $(this).toggleClass("active");
        $(this).next(".menuPanel").slideToggle();
    });
});
Read More
I built many web applications with java and tomcat server. I came across so many problems in handling the flow of programs. Atlast I figured out this below standard way.

Some Standards

  1. Catch exception when you can continue with remaining program  ( Closing statement wont break the process, so you can continue with remaining program)
  2. Throw exception when you can't continue with remaining program  ( Failing to get Database connection will break the process, so you can not continue with remaining program)
  3. Its better to catch exceptions at Servlet, so that it is possible to give appropriate message to user
  4. To avoid SQL Injection attack, Use PreparedStatement to execute queries
  5. Use one Java Class to creating and closing Connections and Statements.
  6. Use one Java Class to execute all queries
  7. Its better to use Pojo classes to carry out data.

DBConn.java

This Java Class is to create Connections and Closing connections and statements.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author srinivas
 * This file is to create Connections and Closing connections and statements.
 */
public class DBConn {
    Connection con = null;
    static String className = "class sodhana.sdb.connection.DBConnection";

    /**
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     * To Create Connections
     */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = null;
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/world", "root", "srinivas");
        return connection;
    }

    /**
     * @param con
     * @param stmt
     * @param rs
     * To close statements, result sets and Connection 
     */
    public static void close(Connection con, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param con
     * @param stmt
     * To close statements and Connection
     */
    public static void close(Connection con, Statement stmt) {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param con
     * @param pstmt
     * @param rs
     * To Close PreparedStatement and Connection
     */
    public static void close(Connection con, PreparedStatement pstmt,
            ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param con
     * To close connection
     */
    public static void closeConnection(Connection con) {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param conn
     * @throws SQLException
     * To Commit and Close the connection
     */
    public static void commitAndClose(Connection conn) throws SQLException {
        conn.commit();
        conn.close();
    }

}

Exception Class for Database Exceptions

Whenever we need to throw an exception, throw the this exception.
public class DBException extends Exception {

    private static final long serialVersionUID = 1L;

    private String message;

    public DBException(String string) {
        message = string;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}

Example

Lets take an example of Employee Table which consists of ID and Name.

EmployeeDAO.java

This java class is for executing all type of  SQL Queries. This is Data Access Object for above Employee Table
public class EmployeeDAO {

    /**
     * @throws DBException 
     * @throws ClassNotFoundException
     * @throws SQLException
     * To Create Table
     */
    public static void createTable() throws DBException {
        Connection conn = null;
        Statement s = null;
        try {
            conn = DBConn.getConnection();
            s = conn.createStatement();
            s.executeUpdate("create table EMP(id varchar(30),name varchar(200),primary key(id))");
            DBConn.close(conn, s);
        } catch (SQLException | ClassNotFoundException e) {
            DBConn.close(conn, s);
            throw new DBException("Excepion while accessing database");
        }

    }

    /**
     * To Drop Table
     * @throws DBException 
     */
    public static void dropTable() {
        Connection conn = null;
        Statement s = null;
            try {
                conn = DBConn.getConnection();
                s = conn.createStatement();
                s.executeUpdate("drop table EMP");
                DBConn.close(conn, s);
            } catch (ClassNotFoundException | SQLException e) {
                DBConn.close(conn, s);
            }
    }

    /**
     * @param emp
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * To Insert Into Data into Table
     */
    public static void insertRow(EmployeePojo emp) throws DBException{
        Connection conn = null;
        PreparedStatement psInsert = null;
        try {
            conn = DBConn.getConnection();
            psInsert = conn.prepareStatement("insert into "
                    + "EMP(id,name) values (?,?)");
            psInsert.setString(1, emp.getId());
            psInsert.setString(2, emp.getName());
            psInsert.executeUpdate();
            DBConn.close(conn, psInsert);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, psInsert);
            throw new DBException("Excepion while accessing database");
        }
    }

    /**
     * @param emp
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * Update data in EMP table
     */
    public static void updateRow(EmployeePojo emp) throws DBException{
        Connection conn = null;
        PreparedStatement psInsert = null;
        try {
            conn = DBConn.getConnection();
            psInsert = conn
                    .prepareStatement("update EMP set name = ? where id = ?");
            psInsert.setString(2, emp.getId());
            psInsert.setString(1, emp.getName());
            psInsert.executeUpdate();
            DBConn.close(conn, psInsert);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, psInsert);
            throw new DBException("Excepion while accessing database");
        }
    }

    /**
     * @param emp
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * To Insert or Update Table
     */
    public static void insertOUpdateRow(EmployeePojo emp) throws DBException{
        if(searchEmployee(emp.getId())){
            updateRow(emp);
        } else {
            insertRow(emp);
        }
    }

    /**
     * @param conn
     * @param id
     * @throws DBException 
     * @throws SQLException
     * To delete data from Table
     */
    public static void deleteRow(String id){
        Connection conn = null;
        PreparedStatement psInsert = null;
        try {
            conn = DBConn.getConnection();
            psInsert = conn
                    .prepareStatement("delete from EMP where id=?");
            psInsert.setString(1, id);
            psInsert.executeUpdate();
            psInsert.close();
            DBConn.close(conn, psInsert);
        } catch (SQLException | ClassNotFoundException e) {
            DBConn.close(conn, psInsert);
        }
    }

    /**
     * @param id
     * @return
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * Read data from Table
     */
    public static EmployeePojo selectEmployee(String id) throws DBException {
        Connection conn = null;
        PreparedStatement psInsert = null;
        ResultSet res=null;
        EmployeePojo emp = new EmployeePojo();
        try {
            conn = DBConn.getConnection();
            psInsert = conn
                    .prepareStatement("select * from EMP where id = ?");
            psInsert.setString(1, id);
            res = psInsert.executeQuery();
            if (res != null) {
                while (res.next()) {
                    emp.setId(res.getString(1));
                    emp.setName(res.getString(2));
                }
            }
            DBConn.close(conn, psInsert, res);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, psInsert, res);
            throw new DBException("Excepion while accessing database");
        }
        return emp;
    }

    /**
     * @param id
     * @return
     * @throws DBException 
     * @throws SQLException
     * @throws ClassNotFoundException
     * To search data
     */
    public static boolean searchEmployee(String id) throws DBException{
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        boolean b = false;
        try {
            conn = DBConn.getConnection();
            ps = conn
                    .prepareStatement("select * from EMP where id = ?");
            ps.setString(1, id);
            res = ps.executeQuery();
            if (res != null) {
                while (res.next()) {
                    b = true;
                }
            }
            DBConn.close(conn, ps, res);
        } catch (ClassNotFoundException | SQLException e) {
            DBConn.close(conn, ps, res);
            throw new DBException("Excepion while accessing database");
        }
        return b;
    }

    /**
     * Droping and Creating Table
     * @throws DBException 
     */
    public static void resetEMP() throws DBException {
            EmployeeDAO.dropTable();
            EmployeeDAO.createTable();
    }

    /**
     * @param args
     * @throws DBException 
     */
    public static void main(String args[]) throws DBException {
        resetEMP();
    }

}

EmployeePojo.java

Use this class to carry information
public class EmployeePojo {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

}

Call DAO from Servlet 

This is the most important part.  If user requests for Insert operation, call insert function in EmployeeDAO.java. If query execution is successful then write success response to user. If query execution is not successful then catch the exception and write failure response to user.
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            EmployeePojo emp = EmployeeDAO.selectEmployee(id);
            String message = " Employee id : "+id +" ----- Employee name : "+emp.getName();
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        } catch (DBException e) {
            e.printStackTrace();
            String message = " Database exception ";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }

Read More

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow this blog by Email

Popular Posts