Java toString Method

Implementing toString method in java is done by overriding the Object’s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object’s Default toString java method.
 class PointCoordnate {  
      private int a, b;  
      public PointCoordnate(int a, int b) {  
           this.a = a;  
           this.b = b;  
      }  
      public int geta() {  
           return a;  
      }  
      public int getb() {  
           return b;  
      }  
 }  
 public class JavaToString {  
      public static void main(String args[]) {  
           PointCoordnate point = new PointCoordnate(20, 20);  
           // using the Default Object.toString() Method  
           System.out.println("Object toString() method : " + point);  
           // implicitly call toString() on object as part of string concatenation  
           String s1 = point + " TEST";  
           System.out.println(s1);  
      }  
 }  

When you run the JavaToString program,
the output is:
Object toString() method : PointCoordnate@119c082
PointCoordnate@119c082 TESTING

In the above example when we try printing PointCoordinate object, it internally calls the Object’s toString() method as we have not overridden the java toString() method. Since out example has no toString method, the default one in Object is used. The format of the default toString method of the Object is as shown below.
Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string. The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer.

getClass().getName() + '@' + Integer.toHexString(hashCode());
Below is an example shown of the same program by Overriding the default Object toString() method. The toString() method must be descriptive and should generally cover all the contents of the object.
 class PointCoordnate {  
      private int a, b;  
      public PointCoordnate(int a, int b) {  
           this.a = a;  
           this.b = b;  
      }  
      public int geta() {  
           return a;  
      }  
      public int getb() {  
           return b;  
      }  
      public String toString() {  
           return "a=" + a + " " + "b=" + b;  
      }  
 }  
 public class JavaToString {  
      public static void main(String args[]) {  
           PointCoordnate point = new PointCoordnate(20, 20);  
           System.out.println("Object toString() method : " + point);            
           String s1 = point + " TESTING";  
           System.out.println(s1);  
      }  
 }  
When you run the JavaToString program,
the output is: a=20 b=20 a=20 b=20 TESTING

Number validation using javascript

 <html>  
 <head>  
 <script>  
 function floatValidation(e,control)  
 {  
   if (e.keyCode==46)  
   {     
     var patt1=new RegExp("\\.");  
     var ch =patt1.exec(control.value);  
     if(ch==".")  
     {  
       e.keyCode=0;  
     }  
   }  
   else if( (e.keyCode>=48 && e.keyCode<=57) || e.keyCode==8)//Numbers or BackSpace  
   {     
     if (control.value.indexOf('.') != -1)//. Exist in TextBox  
     {  
       var pointIndex=control.value.indexOf('.');  
       var beforePoint = control.value.substring(0,pointIndex);  
       var afterPoint = control.value.substring(pointIndex+1);  
       var iCaretPos = 0;  
       if (document.selection)  
       {  
         if (control.type == 'text') // textbox  
         {  
           var selectionRange = document.selection.createRange();  
           selectionRange.moveStart ('character', -control.value.length);  
           iCaretPos = selectionRange.text.length;  
         }  
       }  
       if(iCaretPos > pointIndex && afterPoint.length >= 2)  
       {  
         e.keyCode=0;  
        alert('You enter two digit only after decimal point');  
       }  
       else if(iCaretPos <= pointIndex && beforePoint.length >= 7)  
       {  
         e.keyCode=0;  
       }  
     }  
     else//. Not Exisist in TextBox  
     {  
       if(control.value.length >= 7)  
       {  
         e.keyCode=0;  
         alert('You enter 7 digit only before decimal point');  
       }  
     }  
   }  
   else  
   {  
     e.keyCode=0;  
   }  
 }  
 </script>  
 </head>  
 <body>  
      <input id="amt" type="text" name="Amount" onkeypress="return floatValidation(event,this)" onfocus="setCaretPosition(this,0);"/>  
 </body>  
 </html>  

Why do we need wrapper classes in java?

It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

Configuring Tomcat 6 For https (SSL) Page for Windows

Prerequisites:-
1. JDK
2. Tomcat

For any https (SSL) page a certificate is very necessary. First we will learn generating a keystore, which will contain a certificate chain. We will use the keytool command from JDK.

1. Goto the command prompt.

2. Type keytool -genkey -alias tomcat -keyalg RSA (if your path is not set to the java bin directory, please go there and type the command).

3. Now you will prompted for a keystore password give it as changeit (you can give it different but you will have to make some changes later).

4. Enter the details needed.

5. Now alias password will be aksed. It must be same as keystore password.

6. After the end of it a keystore will be generated in "drive":\Documents and Settings\"username"\.keystore
Now configure "tomcat_home"\conf\server.xml, add the following code:-

  You are done with your configuration. Save the server.xml file. Restart your tomcat. Now type https://localhost:8443

This should show you the same tomcat homepage but in secured format.

Create ireport using struts2, hibernate, spring

Simple iReport generate using struts2.

Download Source: IreportSourceCode

Download JAR file: JARs

Load dependent combo using AJAX, JSP & Servlet


1.index,jsp
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Insert title here</title>  
 <script type="text/javascript" src="script.js">  
 </script>  
 </head>  
 <body>  
 <div align="center">  
      <form name="CountryDetails" >  
           <table>  
                <tr>  
                     <td>State </td>  
                     <td>  
                          <select name="state" id="state" onchange="changeState()">  
                               <option>-- Select State --</option>  
                               <option value="1">Kerala</option>  
                               <option value="3">Tamilnadu</option>  
                          </select>  
                     </td>  
                </tr>  
                <tr>  
                     <td>District Name</td>  
                     <td>       
                          <span id="loadDistrict">  
                               <select name="district" id="district">  
                                    <option>--Select District--</option>  
                               </select>  
                          </span>  
                     </td>  
                </tr>  
           </table>  
      </form>  
 </div>  
 </body>  
 </html>  

2.script.js
 function AjaxFunction()  
 {  
      var xmlrequest=false;  
      try  
      {  
           xmlrequest=new ActiveXObject("Msxml2.XMLHTTP");   
      }  
      catch(e1)  
      {  
           try  
           {  
                xmlrequest=new ActiveXObject("Microsoft.XMLHTTP");   
           }  
           catch(e2)  
           {     
                xmlrequest=false;  
           }  
      }  
      if (!xmlrequest && typeof XMLHttpRequest != 'undefined')   
      {  
           xmlrequest=new XMLHttpRequest();  
      }  
      return xmlrequest;  
 }   
 function changeState()  
 {  
      var state=document.getElementById("state").value;  
      var url="StateDetails?command=statechange&id="+state;  
      var xmlrequest= AjaxFunction();  
      xmlrequest.open("GET",url,true);   
      xmlrequest.onreadystatechange=function()  
      {  
           if(xmlrequest.readyState==4)  
           {  
                if(xmlrequest.status==200)  
                {  
                     //alert(xmlrequest.responseText);  
                     document.getElementById("loadDistrict").innerHTML=xmlrequest.responseText;  
                }  
           }  
      };    
      xmlrequest.send(null);  
 }  

3.StateDetails.java(Servlet)
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import com.mysql.jdbc.Statement;  
 /**  
  * Servlet implementation class StateDetails  
  */  
 public class StateDetails extends HttpServlet {  
      private static final long serialVersionUID = 1L;  
      private static final String CONTENT_TYPE = "text/xml; charset=windows-1252";  
      /**  
       * Default constructor.   
       */  
      public StateDetails() {  
           // TODO Auto-generated constructor stub  
      }  
      /**  
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
       */  
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
           // TODO Auto-generated method stub  
           response.setContentType(CONTENT_TYPE);  
           int stateID=Integer.parseInt(request.getParameter("id").toString());  
           PrintWriter out=response.getWriter();  
           String xml="";  
           int id[]={1,2,3,4,5};  
           String name[]={"Erode","Karur","Trichy","Chennai","Madurai"};  
           try{  
                Connection con=null;  
                Class.forName("com.mysql.jdbc.Driver");  
                con=DriverManager.getConnection("jdbc:mysql://localhost:3036/country","root","");  
                System.out.println("111111111111111");  
                java.sql.Statement statement=con.createStatement();  
                ResultSet rs = statement.executeQuery("SELECT id,district FROM district where stateId="+stateID);  
                xml="<select name=\"district\" id=\"district\">";  
                xml+="<option>--Select District--</option>";  
                while (rs.next()) {  
                     xml+="<option id=\""+rs.getInt(1)+"\">"+rs.getString(2)+"</option>";  
                }  
                xml+="</select>";  
           }  
           catch(Exception e){  
                System.out.println(e.getMessage());  
           }  
           /*xml="<select name=\"district\" id=\"district\">";  
           xml+="<option>--Select District--</option>";  
           for(int i=0;i<5;i++)  
           {  
                xml+="<option id=\""+id[i]+"\">"+name[i]+"</option>";  
           }  
           xml+="</select>";*/  
           out.write(xml);  
      }  
      /**  
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  
       */  
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
           // TODO Auto-generated method stub  
      }  
 }  

Download Source: AJAXExample

Dynamically add check box using javascript

 <html>  
 <head>  
 <script type="text/javascript">  
 function createCheckBox()  
 {  
      var myCheckBoxUnchecked = document.createElement("input");  
      myCheckBoxUnchecked.setAttribute("type","checkbox");  
      myCheckBoxUnchecked.setAttribute("value","checkbox");  
      var myCheckBoxChecked = document.createElement("input");  
      myCheckBoxChecked.setAttribute("type","checkbox");  
      myCheckBoxChecked.setAttribute("value","checkbox");  
      myCheckBoxChecked.checked = true;  
      var handler = document.getElementById("LoadCheckbox");  
      handler.appendChild(myCheckBoxUnchecked);  
      handler.appendChild(myCheckBoxChecked);  
 }  
 </script>  
 </head>  
 <body>  
      <input type="button" value="Create Checkbox" onClick="createCheckBox()" />  
      <div id="LoadCheckbox"></div>  
 </body>  
 </html>