Skip to main content

How to create simple Report in jsp with MySQL database

    Prerequisite

  1. Install Java SDK 1.6 or higher
  2. Install eclipse” Indigo Release”.
  3. Install Tomcat Apache server 6 or 7 version.
  4. Install MySQL 5.5

Jar files

  1. el-api.jar
  2.  iText-2.1.7.jar
  3.   jsp-api.jar
  4.   mysql-connector-java-5.0.5.jar.
  5. servlet-api.jar

Create database  “messageapps” and  “message” Table.


CREATE DATABASE messageapps ;

CREATE TABLE  message(
  massage_id  int(10) unsigned NOT NULL AUTO_INCREMENT,
  name  varchar(45) NOT NULL,
  email  varchar(45) NOT NULL,
  message  varchar(250) NOT NULL,
  time  datetime DEFAULT NULL,
  PRIMARY KEY (massage_id)
) ;

Steps to create PDF Report file 


  1.  Click on File->new->project then select “Dynamic web project “.



    2. Paste the jars file in webContent->WebContent->WEB-INF->lib folder.

    ·         el-api.jar
    ·         iText-2.1.7.jar
    ·         jsp-api.jar
    ·         mysql-connector-java-5.0.5.jar
    ·         servlet-api.jar

    3. Create package in src folder “connector”.

    4. Right click on “connector” package

    5. Select New -> Class , after that windows show

    6. Type “DBConnector” class name.

    7. Write following DBConnector class 


    package connector;
    import java.sql.Connection;
    import java.sql.DriverManager;
    /*
          @auther :Abdul Mugeesh
          this DBConnector class created connection instance.
          getConnection() method return connection object if not exist.
    */
    public class DBConnector {
          public static String url = "jdbc:mysql://localhost:3306/";
          public static String dbName = "messageapps";
          public static String userName = "root";
          public static String password = "root";
                public static Connection getConnection() {
                Connection connection = null;
                if (connection != null)
                {
                      return connection;
                }
                try {
                           
                           Class.forName("com.mysql.jdbc.Driver").newInstance();
                            connection = DriverManager.getConnection(url+dbName,userName,password);
                } catch (Exception e) {
                      e.printStackTrace();
                }
                return connection;
          }
    }


    8.Project hierarchy 

    9. Right Click WebContent->new ->JSP file type JSP filename “pdfGen.jsp” or as you want.

    Write following code 

    <%@page import="javax.swing.border.TitledBorder"%>
    <%@page import="java.sql.Connection"%>
    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.PreparedStatement"%>
    <%@page import="com.lowagie.text.DocumentException"%>
    <%@page import="com.lowagie.text.Paragraph"%>
    <%@page import="com.lowagie.text.html.HtmlWriter"%>
    <%@page import="com.lowagie.text.pdf.PdfWriter"%>
    <%@page import="com.lowagie.text.Document"%>
    <%@page import="java.io.*"%>;
    <%@page import="java.awt.*"%>
    <%@page import="javax.servlet.*"%>
    <%@page import="javax.servlet.http.*"%>
    <%@page import="com.lowagie.text.*"%>
    <%@page import="com.lowagie.text.pdf.*"%>
    <%@page import="com.lowagie.text.html.*"%>
    <%@page import="connector.DBConnector"%>
    <%@page import="java.awt.*"%>
    <%@page import="java.io.IOException"%>
    <%@page import="javax.servlet.*"%>
    <%@page import="javax.servlet.http.*"%>
    <%@page import="com.lowagie.text.*"%>
    <%@page import="com.lowagie.text.pdf.*"%>
    <%@page import="com.lowagie.text.html.*"%>

    <%
    String str="pdf";

    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    try
    {
        Document document=new Document();
        if(str.equals("pdf"))
        {
            response.setContentType("application/pdf");
            PdfWriter.getInstance(document,response.getOutputStream());
        }
        conn= DBConnector.getConnection();
        String query = "select * from message";          //Fetching data from table
           ps=conn.prepareStatement(query);                // executing query
           rs=ps.executeQuery();
          
        document.open();

        /* new paragraph instance initialized and add function write in pdf file*/
        document.add(new Paragraph("---------------------------------------------------------REPORT---------------------------------------------------------\n\n"));
        document.add(new Paragraph("                              CREATED REPORT BY-Abdul Mugeesh\n\n"));
        document.add(new Paragraph("---------------------------------------------------------------------------------------------------------------------------------"));
        document.addCreationDate();
       
        while(rs.next())
        {
              // fetch & writing records in pdf files
            document.add(new Paragraph("MSG_ID ::"+rs.getString(1)+"\nTIME ::"+rs.getString(5)+"\nNAME ::"+rs.getString(2)+"\nEMAIL ::"+rs.getString(3)+"\nMESSAGE ::"+rs.getString(4)+"\n\n"));
        }
        document.add(new Paragraph("---------------------------------------------------------PAGE NO::"+document.getPageNumber()+"------------------------------------------------------"));
       
        document.close(); //document instance closed
        conn.close();  //db connection close
    }
    catch(Exception de)
    {
            de.printStackTrace();
                System.err.println("document: " + de.getMessage());
               
    }


    %>

    10. Start Tomcat server

    11. Run pdfGen.jsp

    It will show you following output

    bingo, Your all tables record will be displayed in PDF file and you can also save this file . 

Comments

Popular posts from this blog

Login and Registration Example in JSP with Session

Those who want to start with jsp and MySQL, this is an excellent example for themselves. Here you can learn how to insert data to MySQL using JSP. Also you can learn about session handling in jsp. 1 2 3 4 5 6 7 8 9 10 CREATE TABLE `members` (    `id` int (10) unsigned NOT NULL auto_increment,    `first_name` varchar (45) NOT NULL ,    `last_name` varchar (45) NOT NULL ,    `email` varchar (45) NOT NULL ,    `uname` varchar (45) NOT NULL ,    `pass` varchar (45) NOT NULL ,    `regdate` date NOT NULL ,    PRIMARY KEY   (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; index.jsp 1 2 3 4 5 6 ...

Timer funcitons in JavaScript: Reminder Script

Timers are used in web pages and we will discuss how to setup one and how to use one with an example. The function setTimeout() in function is used and here is its general syntax. mytime = setTimeout(expression, msec); mytime  is the identifier used to identify the current timeout function.  expression  is the statement that is to be executed after the specified time has ticked off.  msec  is the duration of time in milliseconds after which the expression will be executed.  You can see by using setTimeout function we can execute any function or object after a set of time. For example if msec is set 5000 then the expression will be executed after 5 seconds or 5000 milliseconds.  We will try one example where we will have four period buttons and each button will set a different time for another function to execute and display a alert button. We will call it as a reminder script and we will get one alert box based on the period button we click...

Binary Addition

/* File Name : BinAdd.java */    import java.util.*; public class BinAdd    {  public static String addBit(String a, String b, String c)  { String r=""; if(a.equals("1") && b.equals("0") || a.equals("0") && b.equals("1")) { if( c.equals("0")) r="1"; else { r="0"; c="1"; } } else if( a.equals("0") && b.equals("0") ) { if(c.equals("0")) r="0"; else r="1"; } else if( a.equals("1") && b.equals("1") ) { if(c.equals("0")){ r="0"; c="1"; } else { r="1"; c="1"; } } return c+r; }   public static String add(String a, String b)   { String r=""; int len=a.length(); String carry="0"; for(int i=len-1;i...

Real time changing Clock showing date and time

We can display a clock which will be showing the local time of the client computer by using JavaScript. Note that this time displayed is taken from user computer and not from the server.  We have seen in our  date object example how to display current date and time   where the current date and time is displayed once. Here we will try to display changing clock or real time change in date and time by using  setTimeout function . This setTimeout function we have used to trigger the time display function in a refresh rate of 1000 mill seconds ( 1 Sec ). This refresh rate can be changed to any other value. By changing the value to 5000 the clock will refresh and show the exact time once in every 5 seconds.  Here is the demo of this script and code is given below that.  Sat Apr 23 2016 08:27:22 GMT+0530 (IST)   Here is the code <html> <head> <title>(Type a title for your page here)</title> <script type="text/javascript...