Choose Your Language

Friday 30 October 2015

web application to backup and restore mysql database using jsp and servlets

backupdb.jsp

<%--
    Document   : backupdb
    Created on : Oct 30, 2015, 2:55:19 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="get" action="<%=request.getContextPath()%>/BackupRestoreDataBase" enctype="multipart/form-data">
            <center>
                <br><br><br><br><br><br><br><br><br><br><br><br>
        <table>
            <tr>
                <td>Backup</td>
                <td></td>
                <td><input type="submit" name="backup" value="Backup" id="submit" /></td>
            </tr>
            <tr>
                <td>Restore</td>
                <td><input type="file" name="file" ></td>
                <td><input type="submit" name="restore" value="Restore" id="submit" /></td>
            </tr>
        </table>
     
            </center>
        </form>
    </body>
</html>

BackupRestoreDataBase.java (Servlet)

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class BackupRestoreDataBase extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
         if(request.getParameter("backup")!=null){
              
                 String status=DBBackup.mysqlDatabaseBackUp();
                        if(status.equals("y")){
                          
                            HttpSession session=request.getSession(true);
                            session.setAttribute("currentSessionUser", ""); 
                            response.sendRedirect("backupsuccess.jsp"); 
                        }else if(status.equals("n")){
                            
                            response.sendRedirect("backupfailure.jsp"); 
                        }
                 
            
         }   else if(request.getParameter("restore")!=null){
             
             String fileName=request.getParameter("file");
             
                  boolean status=DBBackup. mysqlDatabaseRestore("dbName","dbUserName","dbPassword","C:\\folderName\\"+fileName);
                  if(status==true){
                      System.out.println("restore success ");
                       HttpSession session=request.getSession(true);
                            session.setAttribute("currentSessionUser", ""); 
                            response.sendRedirect("restoresuccess.jsp");
                  }else{
                       System.out.println("restore failure ");
                       response.sendRedirect("restorefailure.jsp"); 
                  }
            
         } 
    }
}

DBBackup.java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class DBBackup {
 public static boolean mysqlDatabaseRestore(String dbName, String dbUserName, String dbPassword, String source) { 
boolean status=false;
String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source};  
Process runtimeProcess;  
     try {  
runtimeProcess = Runtime.getRuntime().exec(executeCmd);  
int processComplete = runtimeProcess.waitFor();  
if (processComplete == 0) {  
    System.out.println("Backup restored successfully");  
    status =true;
    return status;  
} else{
    System.out.println("Could not restore the backup");
    status=false;
    return status;
}
     }
     catch(Exception ex)
     {
         
     }
     return status;
}
   public static String mysqlDatabaseBackUp() {
       String status="";
       
  File file = new File("C:\\folderName");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
                        
                        String backUpPath= "C:\\folderName";
                        String host="localhost"; 
   String mysqlPort="3306";
   String dbUser="dbUserName";
   String dbPassword ="dbPassword";
   String database ="dbName";    
   DBBackup dbBackup = new DBBackup();
                        try
  {
       DateFormat dayFormat = new SimpleDateFormat("dd");
       DateFormat monthFormat = new SimpleDateFormat("MM");
       DateFormat yearFormat = new SimpleDateFormat("yyyy");
       Calendar cal = Calendar.getInstance();
       String backupDate=dayFormat.format(cal.getTime())+"-"+monthFormat.format(cal.getTime())+"-"+yearFormat.format(cal.getTime());
       byte[] data = dbBackup.getData(host, mysqlPort, dbUser, dbPassword, database).getBytes();   
      
       File fileDestination = new File(backUpPath+"\\"+database+"_"+backupDate+".sql");
       FileOutputStream destination = new FileOutputStream(fileDestination);       
       destination.write(data);
       
       destination.close();
    status="y";
  System.out.println("Back Up Success");
  return status;
  }catch (Exception ex){
       System.out.println("Back Up Failed");
       status="n";
    return status;
    
  }   
                       
} else {
System.out.println("Failed to create directory!");
}
}
        else{
                        String backUpPath= "C:\\folderName";
                        String host="localhost"; 
                        String mysqlPort="3306";
                        String dbUser="root";
                        String dbPassword ="root";
                        String database ="dbName";    
                        DBBackup dbBackup = new DBBackup();
                        try
                         {
       DateFormat dayFormat = new SimpleDateFormat("dd");
       DateFormat monthFormat = new SimpleDateFormat("MM");
       DateFormat yearFormat = new SimpleDateFormat("yyyy");
       Calendar cal = Calendar.getInstance();
       String backupDate=dayFormat.format(cal.getTime())+"-"+monthFormat.format(cal.getTime())+"-"+yearFormat.format(cal.getTime());
       byte[] data = dbBackup.getData(host, mysqlPort, dbUser, dbPassword, database).getBytes();     
      
       File fileDestination = new File(backUpPath+"\\"+database+"_"+backupDate+".sql");
       FileOutputStream destination = new FileOutputStream(fileDestination);       
       destination.write(data);
       
       destination.close();
    
  System.out.println("Back Up Success");
  status ="y";
  return status;
  }catch (Exception ex){
       System.out.println("Back Up Failed");
       status="n";
    return status;
   
  }   
                      
        }
   
 return status;
}
    
    private static ResultSet rs;
    private static Connection con;
    private Statement st;
    private int BUFFER = 99999;
    public String getData(String host, String port, String user, String password, String db) {
        String Mysqlpath = getMysqlBinPath(user, password, db);
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("cant access mysql driver");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + db, user, password);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("connection error");
            e.printStackTrace();
        }
            System.out.println(Mysqlpath);
        Process run = null;
        try {
            System.out.println(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " --compact --complete-insert --extended-insert " + "--skip-comments --skip-triggers " + db);
            run = Runtime.getRuntime().exec(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + "  " + "--skip-comments --skip-triggers " + db);
        } catch (IOException ex) {
           
        }

        InputStream in = run.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuffer temp = new StringBuffer();
   
        int count;
        char[] cbuf = new char[BUFFER];
        try {
            while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
                temp.append(cbuf, 0, count);
            }
        } catch (IOException ex) {
          
        }
        try {
            br.close();
            in.close();
        } catch (IOException ex) {
           
        }
        return temp.toString();
    }

// Mysql path is required to locate the bin folder inside it because it contains the Mysqldump which performs a //main role while taking backup.
/*Function to find MySql Path*/
    public  String getMysqlBinPath(String dbUser, String dbPassword, String databaseName) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("driver loading failed");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + databaseName, dbUser, dbPassword);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("connection error");
            e.printStackTrace();
        }


        String a = "";

        try {
            rs = st.executeQuery("select @@basedir");
            while (rs.next()) {
                a = rs.getString(1);
            }
        } catch (Exception eee) {
            eee.printStackTrace();
        }
        a = a + "bin\\";
        System.err.println("Mysql path is :" + a);
        return a;
    }
}

backupsuccess.jsp

<%-- 
    Document   : backupsuccess
    Created on : Oct 30, 2015, 3:18:39 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>backup success</h1>
    </body>
</html>

backupfailure.jsp

<%-- 
    Document   : backupfailure
    Created on : Oct 30, 2015, 3:18:39 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>backup failure</h1>
    </body>
</html>

restoresuccess.jsp

<%-- 
    Document   : restoresuccess
    Created on : Oct 30, 2015, 3:18:39 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>restore success</h1>
    </body>
</html>

restorefailure.jsp

<%-- 
    Document   : restorefailure
    Created on : Oct 30, 2015, 3:18:39 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>restore failure</h1>
    </body>
</html>

Jar File Needed:

mysql-connector-java-5.1.18-bin.jar

output:



Thursday 22 October 2015

java program to restore mysql database by executing sql file

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class RestoreDatabase {

    public static void main(String ar[]){
        //mysqlDatabaseBackUp();
        String databaseName="qualitychecker";
        String databaseUserName="root";
        String databasePassword="root";
                       /*                       "drive:\\folderName\\fileName"                          */
        String filePathToSqlFile="D:\\test\\qualitychecker_22-10-2015.sql";
        mysqlDatabaseRestore(databaseName,databaseUserName,databasePassword,filePathToSqlFile);
    }
 
    public static void mysqlDatabaseRestore(String dbName, String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source};
Process runtimeProcess;
     try {
        runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();
        if (processComplete == 0) {
            System.out.println("Backup restored successfully");    
        } else{
            System.out.println("Could not restore the backup");
        }
     }
     catch(Exception ex)
     {
       
     }
}
}

java program to backup mysql database

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @Aravind Sankaran Nair
 */
public class BackUpDatabase {
  
    public static void main(String ar[]){
        getMysqlDatabaseBackUp();
    }
   public static void getMysqlDatabaseBackUp() {
   String backUpPath = "D:\\test";   /* driveName:\\folderName      */
   String host="localhost";
   String mysqlPort="3306";
   String dbUser="root";
   String dbPassword ="root";
   String database ="qualitychecker";    /* database bame */
   BackUpDatabase  b = new BackUpDatabase ();
   try
  {
       DateFormat dayFormat = new SimpleDateFormat("dd");
       DateFormat monthFormat = new SimpleDateFormat("MM");
       DateFormat yearFormat = new SimpleDateFormat("yyyy");
       Calendar cal = Calendar.getInstance();
       String backupDate=dayFormat.format(cal.getTime())+"-"+monthFormat.format(cal.getTime())+"-"+yearFormat.format(cal.getTime());
     
 byte[] data = b.getData(host, mysqlPort, dbUser, dbPassword, database).getBytes();
      
       /* To Make Zip file that holding this database use these lines
         File fileDestination = new File(backUpPath+"\\"+database+".zip");
         FileOutputStream destination = new FileOutputStream(fileDestination);
         ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(destination));
         zip.setMethod(ZipOutputStream.DEFLATED);
         zip.setLevel(Deflater.BEST_COMPRESSION);             
         zip.putNextEntry(new ZipEntry(database+"_backup_"+backupDate+".sql"));
         zip.write(data);
         zip.close();
          */
       File fileDestination = new File(backUpPath+"\\"+database+"_"+backupDate+".sql");
       FileOutputStream destination = new FileOutputStream(fileDestination);      
       destination.write(data);
      
       destination.close();
   
  System.out.println("Back Up Success");
  }catch (Exception ex){
       System.out.println("Back Up Failed");
       ex.printStackTrace();
  }        
}
   
    private static ResultSet rs;
    private static Connection con;
    private Statement st;
    private int BUFFER = 99999;
    public String getData(String host, String port, String user, String password, String db) {
        String Mysqlpath = getMysqlBinPath(user, password, db);
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("cant access mysql driver");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + db, user, password);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("connection error");
            e.printStackTrace();
        }
            System.out.println(Mysqlpath);
        Process run = null;
        try {
            System.out.println(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " --compact --complete-insert --extended-insert " + "--skip-comments --skip-triggers " + db);
            run = Runtime.getRuntime().exec(Mysqlpath + "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + "  " + "--skip-comments --skip-triggers " + db);
        } catch (IOException ex) {
        }
        InputStream in = run.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuffer temp = new StringBuffer();
        int count;
        char[] cbuf = new char[BUFFER];
        try {
            while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
                temp.append(cbuf, 0, count);
            }
        } catch (IOException ex) {
        }
        try {
            br.close();
            in.close();
        } catch (IOException ex) {
        }
        return temp.toString();
    }

// Mysql path is required to locate the bin folder inside it because it contains the Mysqldump which performs a //main role while taking backup.
/*Function to find MySql Path*/
    public  String getMysqlBinPath(String dbUser, String dbPassword, String databaseName) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("driver loading failed");
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + databaseName, dbUser, dbPassword);
            st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception e) {
            System.out.print("connection error");
            e.printStackTrace();
        }
        String a = "";
    try {
            rs = st.executeQuery("select @@basedir");
            while (rs.next()) {
                a = rs.getString(1);
            }
        } catch (Exception eee) {
            eee.printStackTrace();
        }
        a = a + "bin\\";
        System.err.println("Mysql path is :" + a);
        return a;
    }

}

Friday 16 October 2015

generate pdf and excel from memory with download option

index.jsp

<%--
    Document   : index
    Created on : Oct 3, 2015, 11:17:49 AM
    Author     : Aravind Sankaran Nair
--%>

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body><br><br><br><br><br><br>
    <center>
        <form method="get" action="<%=request.getContextPath()%>/Report">
        <table cellspacing="0" cellpadding="0" border="0" width="30%">
            <tr bgcolor="#1E90FF">
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
             <%
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/qualitychecker","root","root");
                    Statement st=con.createStatement();
                    ResultSet rs = st.executeQuery("select * from user");  // this is for name
                    while(rs.next())
                    {   int rowCount=rs.getRow();                    
                        if(rowCount%2==0){ %>
                        <tr  bgcolor="#808080">
                            <td><%=rs.getString("firstname")%></td>
                            <td><%=rs.getString("lastname")%></td>
                        </tr>
                         <%}else {%>
                        <tr bgcolor="#D3D3D3">
                            <td><%=rs.getString("firstname")%></td>
                            <td><%=rs.getString("lastname")%></td>
                        </tr>
                          <%  }%>
                   <%  }%>
                 
                     <%
                    rs.close();
                    st.close();
                    con.close();
                    %>
        </table>
        <br><br>
        <input type="submit" name="pdf"  value="PDF">
        <input type="submit" name="excel" value="EXCEL">
        </form>
    </center>
    </body>
</html>

Report.java (Servlet)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class Report extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Report</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Report at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
         if(request.getParameter("pdf")!=null){
             System.out.println("pdf");
             DocumentException ex = null;
    ByteArrayOutputStream baosPDF = null;
             try
{
baosPDF = generatePDFDocumentBytes(request, this.getServletContext());
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                        Calendar cal = Calendar.getInstance();
                        String time=dateFormat.format(cal.getTime());
StringBuffer sbFilename = new StringBuffer();
sbFilename.append("PDFReport_");
                        sbFilename.append(time);
//sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");
response.setHeader("Cache-Control", "max-age=30");
response.setContentType("application/pdf");
StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("attachment");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);
response.setHeader("Content-disposition",sbContentDispValue.toString());
response.setContentLength(baosPDF.size());
ServletOutputStream sos;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}
catch (DocumentException dex)
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println(this.getClass().getName() + " caught an exception: " + dex.getClass().getName()+ "<br>");
writer.println("<pre>");
dex.printStackTrace(writer);
writer.println("</pre>");
}
finally
{
if (baosPDF != null)
{
baosPDF.reset();
}
}
         }else  if(request.getParameter("excel")!=null){
             System.out.println("excel");
             DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
             Calendar cal = Calendar.getInstance();
             String time=dateFormat.format(cal.getTime());
             response.setContentType("application/vnd.ms-excel");
             response.setHeader("Content-Disposition", "attachment; filename=ExcelReport_"+time+".xls");
            
             try{
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet =  hwb.createSheet("new sheet");
sheet.setDefaultColumnWidth(15);
sheet.setColumnWidth(6, 50);
HSSFRow rowhead=   sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("User Id");
rowhead.createCell((short) 1).setCellValue("First Name");
rowhead.createCell((short) 2).setCellValue("Last Name");


Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseName", "databaseUserName", "databasePassword");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from user"); //table
int i=1;
while(rs.next()){     
HSSFRow row=   sheet.createRow((short)i);
row.createCell((short) 0).setCellValue(rs.getInt("uid"));
row.createCell((short) 1).setCellValue(rs.getString("firstname"));
row.createCell((short) 2).setCellValue(rs.getString("lastname"));
i++;
}
hwb.write(response.getOutputStream()); 
  } catch ( Exception ex ) {
    System.out.println(ex);

}
           
         }
    }

    protected ByteArrayOutputStream generatePDFDocumentBytes(
final HttpServletRequest req,
final ServletContext ctx)
throws DocumentException
{
Document doc = new Document();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter docWriter = null;

try
{
docWriter = PdfWriter.getInstance(doc, baosPDF);
doc.addAuthor(this.getClass().getName());
doc.addCreationDate();
doc.addProducer();
doc.addCreator(this.getClass().getName());
doc.addTitle("This is a title.");
doc.addKeywords("pdf, itext, Java, open source, http");
doc.setPageSize(PageSize.LETTER);
HeaderFooter footer = new HeaderFooter(new Phrase("This is a footer."),false);

doc.setFooter(footer);
doc.open();
doc.add(new Paragraph("This document was created on "+ new java.util.Date()));
                        String strServerInfo = ctx.getServerInfo();
                Paragraph paragraph = new Paragraph();
                for(int i=0; i<10; i++){
                    Chunk chunk = new Chunk(" ");
                    paragraph.add(chunk);
                }
                doc.add(paragraph);
                doc.add(createFirstTable());                       
                doc.newPage();
doc.newPage();
}
catch (DocumentException dex)
{
baosPDF.reset();
throw dex; 
}
finally
{
if (doc != null)
{
doc.close();
}
if (docWriter != null)
{
docWriter.close();
}
}

if (baosPDF.size() < 1)
{
throw new DocumentException(
"document has "
+ baosPDF.size()
+ " bytes");
}
return baosPDF;
}
     public static PdfPTable createFirstTable() {
    PdfPTable table = new PdfPTable(2);       
        PdfPCell cell1,cell2;
        
        cell1 = new PdfPCell(new Paragraph("First Name"));
        cell2 = new PdfPCell(new Paragraph("Last Name"));
       
        table.addCell(cell1);
        table.addCell(cell2);
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex);
        }
            Connection con;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseName", "databaseUserName", "databasePassword");
             Statement st;
            st = con.createStatement();
              ResultSet rs=st.executeQuery("Select * from user"); //table name
            int i=1;
            while(rs.next()){            
            table.addCell(rs.getString("firstname"));
            table.addCell(rs.getString("lastname"));            
            i++;
           }
        } catch (SQLException ex) {
            Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex);
        }
      return table;
    }
    
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Report</servlet-name>
        <servlet-class>controller.Report</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Report</servlet-name>
        <url-pattern>/Report</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Jar File Needed

mysql-connector-java-5.1.18-bin.jar //for mysql connection
com.lowagie.text-2.1.7.jar //for pdf
poi-3.9.jar  //for excel

Project Structure

Output:



Thursday 15 October 2015

dynamic table in jsp with alternate row color

index.jsp

<%--
    Document   : index
    Created on : Oct 3, 2015, 11:17:49 AM
    Author     : Aravind Sankaran Nair
--%>

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body><br><br><br><br><br><br>
    <center>
        <table cellspacing="0" cellpadding="0" border="0" width="30%">
            <tr bgcolor="#1E90FF">
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
             <%
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root","root");
                    Statement st=con.createStatement();
                    ResultSet rs = st.executeQuery("select * from user");  // this is for name
                    while(rs.next())
                    {   int rowCount=rs.getRow();                    
                        if(rowCount%2==0){ %>
                        <tr  bgcolor="#808080">
                            <td><%=rs.getString("firstname")%></td>
                            <td><%=rs.getString("lastname")%></td>
                        </tr>
                         <%}else {%>
                        <tr bgcolor="#D3D3D3">
                            <td><%=rs.getString("firstname")%></td>
                            <td><%=rs.getString("lastname")%></td>
                        </tr>
                          <%  }%>
                   <%  }%>
                 
                     <%
                    rs.close();
                    st.close();
                    con.close();
                        %>
        </table>
    </center>
    </body>
</html>

Database 

1. create database testdb;
2. use testdb;
3. CREATE TABLE user (
  `uid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(45) NOT NULL,
  `lastname` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`uid`)
);

4. insert into user values(1,'aravind','sankaran');
5. insert into user values(2,'jayesh','babu');
6. insert into user values(3,'lida','john');
7. insert into user values(4,'bento','rajan');

jar file needed:

mysql-connector-java-5.1.18-bin.jar

Output


Wednesday 14 October 2015

custom css button in jsp

cssbutton.jsp

<%--
    Document   : cssbutton
    Created on : Oct 14, 2015, 1:06:03 PM
    Author     : Aravind Sankaran Nair
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
         <style>
         #body {
         color: red;
         background-color: white;
         font-family: "Times New Roman", Arial, Helvetica, Geneva, "sans-serif";
        }  
        #submit {
        background-color: #ccc;
         -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
        border-radius:6px;
        color:#fff;/*#0033CC;*//* #fff; */
        font-family: 'Oswald';
        font-size: 20px;
        text-decoration: none;
        cursor: poiner;
        border:none;
        }

        #submit:hover {
        border: none;
        color:#fff;
        background:#FF0000;/*red;*/
        box-shadow: 0px 0px 1px #777;
   
        }
        </style>
    </head>
    <body>
        <br><br><br><br><br><br>      
        <h1><center>
            <input type="submit" name="submit" id="submit" value="submit">
            <input type="submit" name="cancel" id="submit" value="cancel">
           </center>
        </h1>
    </body>
</html>

output:




registration page in jsp with javascript validation, captcha security, ajax validation

index.jsp

<%@page import="java.util.TimeZone"%>
<%@page import="java.util.Calendar"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="nl.captcha.Captcha"%>
<%String id = request.getParameter("id");%>


<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>      
        <link href="styles.css" type="text/css" rel="stylesheet" />
        <style>
         #body {
         color: red;
         background-color: white;
        font-family: "Times New Roman", Arial, Helvetica, Geneva, "sans-serif";
        }
        #submit {
        background-color: #ccc;
         -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
        border-radius:6px;
        color:#fff;
        font-family: 'Oswald';
        font-size: 20px;
        text-decoration: none;
        cursor: poiner;
        border:none;
        }

        #submit:hover {
        border: none;
        color:#fff;
        background:#0033CC;
        box-shadow: 0px 0px 1px #777;
 
        }
        </style>
        <script type="text/javascript">
          function validateForm()
            {
            alertify.alert("Message");
           //alumni name
            var alumniname=document.forms["register"]["alumniname"].value;
            if(alumniname==null || alumniname==""){
            alert("Please Provide Alumni Name");
            document.forms["register"]["alumniname"].focus();
            return false;
            }
         
            //registratio type
            if ( ( register.registratiotype[0].checked == false ) && ( register.registratiotype[1].checked == false ) )
            {
                alert ( "Please choose your Registration Type: Student or Employee" );
                return false;
            }
            //course
             var course=document.forms["register"]["course"].value;
            if(course==null || course==""){
            alert("Please Provide Course Name");
           
            return false;
            }
            //completion year
            var completionyear = document.getElementById("completionyear")
            if(completionyear.value == "-select-")
            {
                alert("Please Select Completion Year");
                return false;
            }
            //designation
            var designation = document.forms["register"]["designation"].value;
            if(designation==null || designation==""){
            alert("Please Provide Designation");
            return false;
            }
            //year of joining
            var yearofjoining = document.getElementById("yearofjoining")
            if(yearofjoining.value == "-select-")
            {
                alert("Please Select Year Of Joining");
                return false;
            }
            //present status
            if ( ( register.presentstatus[0].checked == false ) && ( register.presentstatus[1].checked == false ) &&(register.presentstatus[2].checked==false)&&(register.presentstatus[3].checked==false))
            {
                alert ( "Please choose your Present Status: Working Or Business Or Homemaker Or Student" );
                return false;
            }
            //gender
            if ( ( register.gender[0].checked == false ) && ( register.gender[1].checked == false ))
            {
                alert ( "Please choose your Gender: Male Or Female");
                return false;
            }
            //maritalstatus
            if ( ( register.maritalstatus[0].checked == false ) && ( register.maritalstatus[1].checked == false ))
            {
                alert ( "Please choose your Marital Status: Single Or Married");
                return false;
            }
            //phone1
       
            var phone1 = document.forms["register"]["phone1"].value;
         
         
            if (phone1==null||phone1==""){
                   alert("Please Provide Phone Number1");
                 return false;
            }
            else if(isNaN(phone1)||phone1.indexOf(" ")!=-1)
            {
              alert("Please Provide Numeric Value for Phone Number");
              register.phone1.value="";
              return false;
           
            }
            else if (phone1.length>12)
                {
                alert("enter Phone Number With STD Code");    
                register.phone1.value="";
                return false;
             
                }
       
            //phone2
           var phone2 = document.forms["register"]["phone2"].value;
           if (phone2==null||phone2==""){
                alert("Enter Phone Number2");
                return false;
            }
           else if(isNaN(phone2)||phone2.indexOf(" ")!=-1)
           {
              alert("Please Provide Numeric Value for Phone Number");
              register.phone2.value="";
              return false;
           
           }
           else if (phone2.length>12)
           {
                alert("Please Provide Phone Number With STD Code");    
                register.phone2.value="";
                return false;
             
           }
         
            //mobile
          var mobile = document.forms["register"]["mobile"].value;
           if (mobile==null||mobile==""){
                alert("Please Provide Mobile Number");
                return false;
            }
           else if(isNaN(mobile)||mobile.indexOf(" ")!=-1)
           {
              alert("Please Provide Numeric Value as Mobile Number");
              register.mobile.value="";
              return false;
           
           }
           else if (mobile.length>11)
           {
                alert("Please Provide 10 digit value as Mobile Number");
                register.mobile.value="";
                return false;
             
           }
         
          //email
       
          var email = document.getElementById("email")
          var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

            if (!filter.test(email.value)) {
                alert('Please provide a valid email address');
                email.focus;
                return false;
            }
        //address
        var address=document.forms["register"]["address"].value;
            if(address==null || address==""){
            alert("Please provide your address");
            document.forms["register"]["address"].focus();
            return false;
            }
   
                 
             }
</script>

<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
var mobile=document.getElementById("mobile").value;
var urls="checkexistinguser.jsp?mobile="+mobile;

if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4)
    {
        document.getElementById("err").innerHTML=xmlhttp.responseText;
     }
  }
xmlhttp.open("GET",urls,true);
xmlhttp.send();
}
</script>
    </head>
    <body id="">
    <center>
     
        <form  name="register" action="/Captcha/validatecaptcha.jsp" method="get" onsubmit="return validateForm();">
         <table border="0" cellpadding="10" cellspacing="1" BORDERCOLOR=#0B2161 style="width:80%">
  <tr>
    <td align="left" width="20%">Name of the Alumni:</td>
    <td align="left" width="60%">      
        <input type="text" name="alumniname" id="alumniname" size="45">      
    </td>  
  </tr>
  <tr>
  <td width="20%" align="left" border="0"><Font size="5" color="#8904B1">STUDENT</Font></td>
  <td width="60%">&nbsp;</td>
  </tr>
 
  <tr>
    <td align="left" width="20%">Registration Type:</td>
    <td align="left" width="60%">
    <input type="radio" name="registratiotype" id = "1" value="Student">Student&nbsp;&nbsp;&nbsp;
<input type="radio" name="registratiotype" id = "2" value="Employee">Employee
    </td>  
  </tr>

  <tr>
    <td align="left" width="20%">Course:</td>
    <td align="left" width="60%"><input type="text" name="course" id="course" size="45"></td>  
  </tr>

   <tr>
    <td align="left" width="20%">Year of completion:</td>
    <td align="left" width="60%">  
    <select name="completionyear" id="completionyear" style="width: 80px;">
    <option value="-select-">-select-</option>
<%
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
int currentYear = localCalendar.get(Calendar.YEAR);
for(int i=currentYear;i>1947;i--)
{%>
<option value= "<%= i%>" <%=i%>><%= i%></option>
<%}%>
</select>
    </td>  
  </tr>
  <tr>
  <td width="20%" align="left" border="0"><Font size="5" color="#8904B1">EMPLOYEE</Font></td>
  <td width="60%">&nbsp;</td>
  </tr>
   <tr>
    <td align="left" width="20%">Designation:</td>
    <td align="left" width="60%"><input type="text" name="designation" id="designation" size="45"></td>      
  </tr>

   <tr>
    <td align="left" width="20%">Year of joining: </td>
    <td align="left" width="60%">
    <select name="yearofjoining" id="yearofjoining" style="width: 80px;">
    <option value="-select-">-select-</option>
<%
for(int i=localCalendar.get(Calendar.YEAR);i>1947;i--)
{%>
<option value= "<%= i%>" <%=i%>><%= i%></option>
<%}%>
    </td>  
  </tr>

   <tr>
    <td align="left" width="20%">Present status:</td>
    <td align="left" width="60%">
    <input type="radio" name="presentstatus" id="1" value="Working">Working&nbsp;&nbsp;&nbsp;
<input type="radio" name="presentstatus" id="2" value="Business">Business&nbsp;&nbsp;&nbsp;
<input type="radio" name="presentstatus" id="3" value="Homemaker">Homemaker&nbsp;&nbsp;&nbsp;
<input type="radio" name="presentstatus" id="4" value="Student">Student
    </td>  
  </tr>

  <tr>
    <td align="left" width="20%">Gender:</td>
    <td align="left" width="60%">
    <input type="radio" name="gender" id="1" value="Male">Male&nbsp;&nbsp;&nbsp;
<input type="radio" name="gender" id="2" value="Female">Female
    </td>  
  </tr>

  <tr>
    <td align="left" width="20%">Marital Status:</td>
    <td align="left" width="60%">
    <input type="radio" name="maritalstatus" id="1" value="Single">Single&nbsp;&nbsp;&nbsp;
<input type="radio" name="maritalstatus" id="2" value="Married">Married
    </td>  
  </tr>
  <tr>
  <td width="25%" align="left" border="0"><Font size="5" color="#8904B1">CONTACT INFORMATION</Font></td>
  <td width="55%">&nbsp;</td>
  </tr>
  <tr>
    <td align="left" width="20%">Phone No 1:</td>
    <td align="left" width="60%"><input type="text" name="phone1" id="phone1" size="45"></td>  
  </tr>

  <tr>
    <td align="left" width="20%">Phone No 2:</td>
    <td align="left" width="60%"><input type="text" name="phone2" id="phone2" size="45"></td>  
  </tr>

  <tr>
    <td align="left" width="20%">Mobile:</td>
    <td align="left" width="60%"><input type="text" name="mobile" id="mobile" onkeyup="loadXMLDoc()" size="45">&nbsp;<span id="err"></span></td>  
  </tr>

  <tr>
    <td align="left" width="20%">Email:</td>
    <td align="left" width="60%"><input type="text" name="email" id="email" size="45"></td>  
  </tr>

  <tr>
    <td align="left" width="20%">Address:</td>
    <td align="left" width="60%"><textarea rows="4" cols="47" name="address" id="address"></textarea></td>      
  </tr>

   <tr>
    <td align="left" width="20%"><font color="red">Security code *</font></td>
    <td align="left" width="60%"><img id="captcha" src="<c:url value="simpleCaptcha.jpg"/>" width="150"></td>      
  </tr>
  <tr>
    <td align="left" width="20%">Please enter the Verification Code shown in the image above.</td>
    <td align="left" width="60%"><input type="text" size="17" name="answer" /></td>      
  </tr>
  <tr>
    <td align="left" width="20%">&nbsp;</td>
    <td align="left" width="60%">
     
        <input type="submit" name="submit" value="    Register    " id="submit" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="submit" name="cancel" value="     Cancel     " id="submit" />
    </td>      
  </tr>
 </table>
            <br></br>
     
       </form>
</center>
<input type="text" hidden="" name="yes"  value="<%=id%>"/>
 
 </body>
</html>

validatecaptcha.jsp

<%-- 
    Document   : validatecaptcha
    Created on : Sep 7, 2015, 4:33:35 PM
    Author     : Aravind Sankaran Nair
--%>
<%@page import="com.captcha.bean.RegistrationBean"%>
<%@ page import="nl.captcha.Captcha"%>
<%
Captcha captcha=(Captcha)session.getAttribute(Captcha.NAME);

request.setCharacterEncoding("UTF-8");

String answer = request.getParameter("answer");
                                 
if (captcha.isCorrect(answer)) {
  
    session=request.getSession(true);
    session.setAttribute("", "");
    response.sendRedirect("index.jsp");  
%>

<center><b>Correct Captcha Code !</b> <%

} else {
response.sendRedirect("index.jsp"); 
%> <b>In Correct Captcha Code !</b> <%

}

%>
</center>

checkexistinguser.jsp

<%@ page import="java.io.*,java.sql.*"%>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>

<%
  String mobile=request.getParameter("mobile");
  if(mobile.length()!=0){
  Class.forName("com.mysql.jdbc.Driver");
  Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","dbusername","dbpassword");
  Statement st=con.createStatement();              
  ResultSet rs = st.executeQuery("select * from table where mobile='"+mobile+"'");  // this is for name
  if(rs.next())
    {%>     
<font color=red>Already Registered<input type="hidden" id="actual" name="actual" value="taken"></font>
<% }else {%>
<font color=green size="3"><input type="hidden" id="actual" name="actual"value="available">Not Registered </font>
<% }%>
 <% 
 rs.close();
 st.close();
 con.close();
  }else{ %>
 <font color=red><input type="hidden" id="actual" name="actual" value="taken"> </font>
 <%} %>
  

style.css 

body {

color: red;

background-color: white;

font-family: "Times New Roman", Arial, Helvetica, Geneva, "sans-serif";

}
.btnExample {
  color: #FFF;
  background-color: #900;
  font-weight: bold;
  border: 1px solid #900;
}
.btnExample:hover {
  color: #FFF;
  background: #900;
}
#submit {
    background-color: #ccc;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:6px;
    color: #fff;
    font-family: 'Oswald';
    font-size: 20px;
    text-decoration: none;
    cursor: pointer;
    border:none;
}