Saturday, November 5, 2011

Passing variable values from one jsp to another jsp

Here is a very simple example to pass variable value from one jsp to another jsp.


Main JSP where variables are initialized.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Display</title>
    </head>

    <SCRIPT LANGUAGE="JavaScript">
        var no = 4;
        var eventName = new Array(no);


        eventName[3] = "E1";
        eventName[2] = "E2";
        eventName[1] = "E3";
        eventName[0] = "E4";
       
        function getDetails()
        {
            //window.location = "./Timeline - All.html";
            window.open('./child.jsp','','scrollbars=no,menubar=no,height=600,width=800,resizable=no,toolbar=no,location=no,status=no');
        } 
            
    </SCRIPT>

    <body>
        <h1>Hello!</h1>
        <form name ="f1" method="post">
            <table border="0" cellpadding="30">
                <tr>
                    <td>
                        <font size="3" face="arial" color="Black">Enter ID</font>
                    </td>
                    <td>
                        <input type="text" name="id">
                    </td>
                </tr>   

                <tr>
                    <td>
                        <input type="button" value="Submit" name="showId" onclick="getDetails()"/>
                    </td>
                </tr>

            </table>
        </form>

    </body>

</html>


Child JSP where we get the values of main jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Child</title>
    </head>

    <SCRIPT LANGUAGE="JavaScript">
        var no = 4;
        var eventName = window.opener.eventName;
       
       
        function getDetails()
        {
            for(i=0;i<no;i++) {
                alert(eventName[i]);
            }
        } 
            
    </SCRIPT>

    <body onload="getDetails()">

    </body>

</html>

Dynamically create table, rows, cells in html - JSP

In JSP, we have created html, table, rows (tr) and cells (td). However few days back, I was given challenge to create it dynamically based on some values returned from the database.


Below, I will show you how to create cells and rows dynamically.


based on some values returned from the database.

Below, I will show you how to create cells and rows dynamically.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>Customer Timeline Display</title>
        <script>
           
            function isEven(value) {
                if (value%2 == 0)
                    return true;
                else
                    return false;
            }

           
            function start() {
                var eventName = new Array(4);
                var eventDate = new Array(4);
                eventName[0] = "Olympic";
                eventName[1] = "Asian Games";
                eventName[2] = "Grand Prix";
                eventName[3] = "Football World Cup";

                eventDate[0] = "2003";
                eventDate[1] = "2005";
                eventDate[2] = "2007";
                eventDate[3] = "2011";
               
                // get the reference for the body
                var mybody = document.getElementsByTagName("body")[0];
                // creates table and tbody elements
                mytable     = document.createElement("table");
                mytablebody = document.createElement("tbody");

                // creating all cells
                for(var j = 0; j < eventName.length; j++) {
                    // creates a <tr> element
                    var event = eventName[j];
                    mycurrent_row = document.createElement("tr");

                    for(var i = 0; i < 3; i++) {
                        // these should be always 3 as 3 columns
                        // creates a td element
                        mycurrent_cell = document.createElement("td");
                        mycurrent_cell.setAttribute("width",300);
                           
                        // creates a Text Node
                        if(isEven(j)) {
                            if(i == 2) {
                                currentText = document.createTextNode(eventName[j] + " on " + eventDate[j]);
                                mycurrent_cell.appendChild(currentText);
                                mycurrent_cell.setAttribute("align", "center");

                            }
                        }
                        if(!isEven(j)) {
                            if(i == 0) {
                                currentText = document.createTextNode(eventName[j] + " on " + eventDate[j]);
                                mycurrent_cell.appendChild(currentText);
                                mycurrent_cell.setAttribute("align", "center");
                            }
                        }
                        // appends the Text Node we created into the cell <td>

                        if(i == 1) {
                            mycurrent_image = document.createElement("img");
                            if(event == "Olympic") {
                                mycurrent_image.setAttribute("src","1.jpg");
                                mycurrent_image.setAttribute("height",60);
                                mycurrent_image.setAttribute("width",60);
                            } else if(event == "Asian Games") {
                                mycurrent_image.setAttribute("src","2.jpg");
                                mycurrent_image.setAttribute("height",60);
                                mycurrent_image.setAttribute("width",60);
                            } else if(event == "Grand Prix") {
                                mycurrent_image.setAttribute("src","3.jpg");
                                mycurrent_image.setAttribute("height",60);
                                mycurrent_image.setAttribute("width",60);
                            } else if(event == "Football World Cup") {
                                mycurrent_image.setAttribute("src","4.jpg");
                                mycurrent_image.setAttribute("height",60);
                                mycurrent_image.setAttribute("width",60);
                           
                            mycurrent_cell.appendChild(mycurrent_image);
                            mycurrent_cell.setAttribute("bgColor","##BC8F8F");
                            mycurrent_cell.setAttribute("width",10);
                            mycurrent_cell.setAttribute("align","center");
                        }
                        // appends the cell td into the row tr
                        mycurrent_row.appendChild(mycurrent_cell);
                    }
                    // appends the row tr into tbody
                    mytablebody.appendChild(mycurrent_row);
                }

                // appends tbody into  table
                mytable.appendChild(mytablebody);
                // appends table into body
                mybody.appendChild(mytable);
                // sets the border attribute of mytable to 0;
                mytable.setAttribute("border","0");
                mytablebody.setAttribute("bgColor", "#FFF5EE");
                mytable.setAttribute("align","center");
               
            }
        </script>
    </head>
    <body onload="start()">
    </body>
</html>


Hope you find it useful.

Sunday, October 30, 2011

Java Code to connect to oracle database and call query with PreparedStatement Class

Below is the simple example to connect to oracle database and to call queries using PreparedStatement Class.




Connect to database:



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;



public class DBConnection {





DBConnection() {

}



protected Connection dbInitiateConnection() {

Connection con = null;

String dbHost = “dbhost";

String dbPort = dbport;

String dbSid = dbsid;

String dbUsername = dbusername;

String dbpassword = dbpassword;





try {

Class.forName("oracle.jdbc.driver.OracleDriver");

} catch (ClassNotFoundException ex) {

ex.printStackTrace();

} catch (NullPointerException npe) {

npe.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}



try {

con = DriverManager.getConnection("jdbc:oracle:thin:@" + dbHost + ":" + dbPort + ":" + dbSid, dbUsername, dbpassword);

con.setAutoCommit(false);

} catch (SQLException se) {

se.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}



return con;

}

}







Calling the queries to database:

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;



public class DBDetails {



protected void getDateDetailsFromDatabase(Connection con) {

String queryDate = "select sysdate from dual";



try {

PreparedStatement psDate = con.prepareStatement(queryDate);

ResultSet rsDate = psDate.executeQuery();



while (rsDate.next()) {

java.sql.Date date = rsDate.getDate(1);

System.out.println(date.toString());

}

} catch (SQLException ex) {

ex.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

con.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}



protected void getTableDetailsFromDatabase(Connection con) {

String queryAllTables = "SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME LIKE 'E%' AND ROWNUM <= 10";

try {

PreparedStatement psAllTables = con.prepareStatement(queryAllTables);

ResultSet rsAllTables = psAllTables.executeQuery();



while (rsAllTables.next()) {

String table_name = rsAllTables.getString(1);

System.out.println(table_name);

}

} catch (SQLException ex) {

ex.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

con.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}




protected String getCreatedDateDetailsFromDatabase(Connection con, String customerID) {



String queryDate = "a_query";

//put any query you like, here I am assuming that you are trying to extract the date from a table.

String createdDate = new String("");



System.out.println(queryDate);

try {

PreparedStatement psDate = con.prepareStatement(queryDate);

ResultSet rsDate = psDate.executeQuery();



while (rsDate.next()) {

java.sql.Date date = rsDate.getDate(1);

createdDate = date.toString();

System.out.println(createdDate);

}

} catch (SQLException ex) {

ex.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

con.close();

} catch (Exception e) {

e.printStackTrace();

}

}



return createdDate;

}



}













Main class to call the other classes:





import java.sql.Connection;



public class Main {





public static void main(String[] args) {

DBConnection dbConnection = new DBConnection();

DBDetails dbDetails = new DBDetails();



Connection con = dbConnection.dbInitiateConnection();



if (con != null) {

dbDetails.getDateDetailsFromDatabase(con);

}
}
}

Thursday, September 8, 2011

How to Create JDBC Connection Pool In Weblogic

Open weblogic admin console (home page) and go to “Services” tab in the left panel.


Click on “JDBC” on the right panel. It will open the following screen.



Click on “Data Sources”. It will open the following screen. Then click on “New” to create a new Connection Pool.

Enter the required details as shown for the below screen


Name : Enter appropriate name for the connection pool.
JNDI Name : Enter appropriate JNDI name for the connection pool.
Database Type : Select appropriate database type. In case of CPS its “Oracle”.

Database Driver : Select appropriate database driver. In case of CPS its “Oracle’s Driver (Thin)

Versions :9.0.1, 9.2.0,10,11”.
Click on “Next” after entering the details.

 
Click on “Next” once the below screen appears.


Enter the required connection properties for the database connection as shown below :

Database Name : Enter the appropriate database name (i.e. Service Identifier of the database).

Host Name : Enter the appropriate host IP address of database.

Port : Enter the appropriate Port No to connect to database.

Database User Name : Enter the appropriate database User Name to connect to database.

Password : Enter the appropriate password to connect to database.

Confirm Password : Enter the password again for confirmation.



Click on “Next” after entering the connection properties.



 
On clicking “Next” two more text area appears. Click on “Test Configuration” to test whether the connection is successfully established or not.

A message appears on the top of the screen stating whether the connection test is successful or not.

If the test is successful, click on “Next”.


Then create a new JDBC Data Source. Select a server from the list displayed on the screen. If the desired server name is not displayed on the screen, then go to targets and select the appropriate server name.



 
Then Click on “Finish”.




The following screen will appear which indicates that the datasource is successfully created.



 
If the properties of the connection pool needs to be changed at any point of time, then click on the datasource name displayed on the previous step. The following screen will appear.


Navigate through the displayed tabs to view the various connection pool related properties. If required, edit them and click on “Save”. The edited properties will be saved.

Tuesday, July 26, 2011

XML Creation On the Fly - Java Source Code

In my earlier article, I have shown you how to create the XML file using java APIs. Here I will show you how to do the same however without actually creating files. Here I will use the String buffer to hold the XML content that can be used to do further processing if needed.
 @Credit: Sumeet Chakraborty
Java API being used here is same as one earlier.
Another API being used:

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLCreation {

      public static void main(String args[]) {

            XMLCreation xmlCreate = new XMLCreation();
            xmlCreate.createXML();
      }

      private void createXML() {

            String customerName = "Ramesh";
            String customerAddress = "Delhi";

            DocumentBuilder domBuilder = null;
            try {
                  DocumentBuilderFactory domFactory = DocumentBuilderFactory
                              .newInstance();
                  domBuilder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException pcEx) {
                  System.out
                              .println("ParserConfiguration  "
                                          + pcEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured"
                                          + e.getMessage());
            }
            Document newDoc = domBuilder.newDocument();

            // Root element
            Element rootElement = newDoc.createElement("CustomerInformation");
            newDoc.appendChild(rootElement);

            // Creating element containing value Name
            Element curElement = newDoc.createElement("Name");
            curElement.appendChild(newDoc.createTextNode(customerName));
            rootElement.appendChild(curElement);

            // Creating element signifies address
            Element keyElement = newDoc.createElement("Address");
            keyElement.appendChild(newDoc.createTextNode(customerAddress));
            rootElement.appendChild(keyElement);

            DOMSource sourceInt = new DOMSource(newDoc);

           
            //This will hold the XML content being built later on
//This is the difference where we are not creating file
//Instead, we are using StringWriter to hold the XML content
            StringWriter stew = new StringWriter();

            // File stew = new File("C:/sampleXMLfile.xml");

            StreamResult resultInt = new StreamResult(stew);

            TransformerFactory tFactoryInt = TransformerFactory.newInstance();
            Transformer transformerInt = null;

            try {
                  transformerInt = tFactoryInt.newTransformer();
                 
                  //this is where actually transformation happens and creates the XML
                 
                  transformerInt.transform(sourceInt, resultInt);
                  System.out.println("XML created as " + stew.getBuffer().toString());
            } catch (TransformerException tEx) {
                  System.out
                              .println("TransformerException Occured  "
                                          + tEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured                                           + e.getMessage());
            }

      }
}

Total Pageviews