August 21, 2012

To call external css class using jquery

How to call an external css class using jquery.

There are two ways to apply css through jquery

addClass("your css class name");

addClass will only append the new class to the existing one. so we have to remove the existing class using removeClass(" your css class name") method.

removeClass() is used to remove all the css class.

css() is used to apply style to a specific html component.

How to ?

html : file.html
<p id="powerballNumbers"> Hunger Games, Newsweek, </p>
<div id ="RioDeJaneiro" class ="McllroyClass"></div>

jquery : file.js
$("#powerballNumbers").css({"background":"yellow"});
$("#RioDeJaneiro").removeClass("McllroyClass").addClass("rihana");

css: file.css
.rihana
{
width : 10px;
height : 5 px;
backgroud : url (img_mileycyrus.gif) 0 0;
}

How to create a web application with jquery :  a simple web application

http://belazy.blog.com/

August 13, 2012

How to compare a string with a string in notepad using command prompt

To compare a string with a string in notepad using command prompt



http://belazy.blog.com/

August 09, 2012

Program to find LCM and HCF in java

Description : A program in java to find least common multiple and Highest common factor

 import java.util.Scanner;


public class LCM {

    /**
     * Computer Science practical question for exams
     */
    private Scanner scanner_ins = null; // To scan user inputed value
   
    private int totalNumber = 0;         //     totalNumber by user
    private int minimumValue = 0;       //     Minimum value inside the user inputed array
    private int lcm = 1;
    private int hcf = 1;
   
    private int [] value_array = null;  // User entered value
   
   
    private int [] denominators = {1,9,8,7,6,5,4,3,2};
    //private int [] commonMultiples = null;
   
   
    /**
     * Constructor
     */
    LCM(){
        scanner_ins = new Scanner(System.in);
    }
   
   
    private void getUserInputs() {
        // TO get user input  Total elements
        System.out.println(" Enter the total number of elements (Say n) : ");
        totalNumber = scanner_ins.nextInt();   //as like scanf, cin in cpp
      
        value_array = new int[totalNumber];  // initialized the size of array
      
      
        for(int i =0 ;i < totalNumber; i++)   //This for loop used to get the elements from user
        {
            System.out.print(" Enter the "+(i+1)+"th elements : ");
            value_array[i]=scanner_ins.nextInt();
        }
      
    }
   
   
    private void findMinimumValue() {
        // TO Find Minimum value inside value_array[]
      
        int temp =0;   // A temporary variable
        temp = value_array[0];  // assingning first value of array to temp
      
        for(int i=1; i< totalNumber; i++)  // For loop compare the temp values to all other values in the array
        {
            if(temp > value_array[i])
            {
                temp = value_array[i];       // changing the temp value to minimum
            }
          
        }
        minimumValue = temp;
    }
   
   
   

    private void findCommomMultiples() {
        // TODO Auto-generated method stub
        denominators[0] = minimumValue;
        int reminder =0;   // reminder
        boolean isCommonMultiper = false;  // is a common multipler
        for(int denoPstn =0; denoPstn < denominators.length; denoPstn ++)
        {
            System.out.println("deno : "+ denominators[denoPstn]);
            System.out.println();
            for(int valuePstn = 0; valuePstn < totalNumber; valuePstn++)
            {
                reminder = value_array[valuePstn] % denominators[denoPstn];
                System.out.println(" value "+ value_array[valuePstn]);
                if(reminder == 0)
                {
                    isCommonMultiper = true;
                    continue;
                }
                else
                {
                    isCommonMultiper = false;
                    break;
                }
              
            }
            if(isCommonMultiper == true)
            {
                lcm = lcm * denominators[denoPstn];
              
                for(int i = 0; i < totalNumber ; i++)
                {
                    if(value_array[i] !=0)
                    value_array[i] = value_array[i] / denominators[denoPstn];
                    else if(value_array[i]==1)
                        System.out.println(" got 1");
                  
                    System.out.print("  value "+ value_array[i]);
                  
                }
            }
            //System.out.println(" reminder :"+ reminder);
        }
        hcf = lcm;
    }
   
   

    private void findLCM() {
        // TO calculate Lcm
      
        for(int i=0; i < value_array.length; i++)
        {
            lcm = lcm * value_array[i];
        }
      
    }
   
   
   
   
    public static void main(String[] highestCommonfactor) {
        // main class where program starts
        LCM lcm_ins = new LCM();  //instance (ins) of Lcm class
        lcm_ins.getUserInputs();  //for getting user input (total elements, elements into array)
        long startTime = System.currentTimeMillis();
        lcm_ins.findMinimumValue();  //To find minimum value user inputed
        lcm_ins.findCommomMultiples();
        lcm_ins.findLCM();
        lcm_ins.showDetails((System.currentTimeMillis() - startTime));
    }




    private void showDetails(long timeTaken) {
      
        System.out.println("\n\t PRIME FACTORS \n ");

      
        System.out.print("\n\t User inputs   [ ");
        for(int i = 0 ; i < totalNumber ; i++)   //This for loop used to user inputed values
        {
            System.out.print(" " + (value_array[i] * hcf));
        }
        System.out.println(" ]");
      
      
        System.out.print("\n\t After dividing by common multiples   [ ");
        for(int i = 0 ; i < totalNumber ; i++)   //This for loop used to view value array after iteration
        {
            System.out.print(" " + value_array[i]);
        }
        System.out.println(" ]");
      
      
        System.out.println("\t  H C F is "+hcf);
        System.out.println("\t  L C M is "+lcm);
      
        System.out.println("\t Computation Time : "+timeTaken+" ms");
      
    }

   

}
 




The above  program is just a simple one. Check here to know how to find the missing number in a sequence. the number is inserted randomly. I hope the complexity is minimum b-lazy java


Similar posts


Finding HCF and LCM

Finding Factorial using recursion

Fibonacci series

Binary search in java

Palindrome in java

Geometric mean using java 

Prime number in java

Print triangle in java

Find missing number in java


Java Source codes

How to print matrix in java

Matrix Manipulation in java


Description : To print sum of all values of matrix in java


 import java.util.Scanner;

/**
* +belazy 
*/
/**
* @author BlackBery
*
*/
public class MatrixDiagonal {
private int [][]matrix = null;
private Scanner sc = null;
public MatrixDiagonal() {
matrix = new int[3][3];
}
public static void main(String[] args) {
MatrixDiagonal md = new MatrixDiagonal();
md.getMatrixValues();
md.showMatrix();
md.computeValue();
}
private void computeValue() {
int sum = 0;
for(int row = 0; row < 3 ; row ++){
for(int col =0; col col){
sum = sum + matrix[row][col];
}
}
}
System.out.println(sum);
}
private void showMatrix() {
for(int row = 0; row < 3 ; row ++){
for(int col =0; col < 3; col ++ ){
System.out.print(matrix[row][col]+"\t");
}
System.out.println();
}
}
private void getMatrixValues() {
sc = new Scanner(System.in);
System.out.println(" Enter values ");
for(int row = 0; row < 3 ; row ++){
for(int col =0; col < 3; col ++ ){
matrix[row][col] = sc.nextInt();
}
}
}
}

ajax jquery call to servlet example

How to call a servlet using jquery ajax

Description : This is a small example to call servlet using ajax jquery. also shows servlet mapping in web.xml file (Deployment descriptor) .How to use external javascript file in java[ajax servlet Tutorial].








web.xml

<servlet>
    <description></description>
    <display-name>AjaxServlet</display-name>
    <servlet-name>AjaxServlet</servlet-name>
    <servlet-class>servlets.AjaxServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AjaxServlet</servlet-name>
    <url-pattern>/AjaxServlet</url-pattern>
  </servlet-mapping>

 <welcome-file>index.jsp</welcome-file>


index.jsp

jquery api needed

<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="myJquery.js"></script>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<div>
<input type="text" id="headText">
<input type="button" id="newButton" value="sendData">
</div>



servlet : AjaxServlet.java

public class AjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(" inside do post "+request.getParameter("message"));
    }

}

jquery file : myjquery.js

$(document).ready(function(){
  $('#newButton').click(function(){
           sendData();
    });
   });
function sendData(){
   var mge = $('#newText').val();
    alert(mge);
    $.ajax({
        type: "POST",
        url: "AjaxServlet",
        data: { message : mge  }
      }).done(function( msg ) {
        alert( "Data Saved: " + msg );
      });
}

Description : The Example show how to call a servlet from jsp using ajax jquery. Data from jsp page will pass to servlet as parameter through ajax call


To receive response from the servlet, Change the code to following

In servlet

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws    ServletException, IOException {
        String message = request.getParameter("message");
         String respMess = message + "data saved ";
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(respMess);
    }

In jquey

The function sendData() will send data to post method of servlet "JqueryServlet". the data is taken from html tag whose id is " headText ". In the example i have created a text box named headtext in Index.jsp (java server page)

function sendData(){
    var mge = $('#headText').val();
   
    $.ajax({
          type: "POST",
          url: "JQueryServlets",
          data: { message : mge},
          success : function(data){
              alert('success'+data);
          }
        });
   
}



Thanking you for reading this post. Hope you will try the code...

Your feedback may help rest of the readers... so please, your valuable comments


Now take a look how cascading style sheet is applied in struts, that is a constant look and feel for all your web pages in your web application . >>> lazy java

August 05, 2012

Compare database mysql date with current date

 Comparing mysql database date with current java date
/**
 *
 */
package Date;



import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author deep
 *
 * program compares todays date with that in db
 *
 */






public class JavaDate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String dateInDB = "2011-1-12";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = format.format(new Date());
        System.out.println(" Current date : " +currentDate);
        System.out.println(" date in db   : " +dateInDB);
        if(currentDate.compareTo(dateInDB) <= 0)
            System.out.println("current date is greater ");
        else
            System.out.println("db date is greater ");
    }

}


Thanking you....

Ajax Java Servlet Example

How Ajax works with java example 

Introducing AJAX : asynchronous java and xml for Java web application , Here is a simple example
The below example shows you how java servlet response/replies to ajax request/call from a jsp page. The java server page need not be reload again, only the div refresh. Please try the source code.


Deployement Descriptor : web.xml




 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Java ajax call</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>nextgeneration.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ForAjax</display-name>
    <servlet-name>ForAjax</servlet-name>
    <servlet-class>ForAjax</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ForAjax</servlet-name>
    <url-pattern>/ForAjax</url-pattern>
  </servlet-mapping>
</web-app>



XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX  

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>Nexegen Technologies</title>
<script type="text/javascript" src="ajax.js"></script>

</head>
<body>

<div id="ajaxDiv">
</div>

<div id = "mydiv">
<input type="button" onclick="verifyPassword()">
</div>

</body>
</html>

XXX XXX XXX XXX XXX XXX XXX XXX XXX


Ajax.js
/*
 * creates a new XMLHttpRequest object which is the backbone of AJAX,
 * or returns false if the browser doesn't support it
 */
function getXMLHttpRequest() {
  var xmlHttpReq = false;
  // to create XMLHttpRequest object in non-Microsoft browsers
  if (window.XMLHttpRequest) {
    xmlHttpReq = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      // to create XMLHttpRequest object in later versions
      // of Internet Explorer
      xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (exp1) {
      try {
        // to create XMLHttpRequest object in older versions
        // of Internet Explorer
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (exp2) {
        xmlHttpReq = false;
      }
    }
  }
  return xmlHttpReq;
}
/*
 * AJAX call starts with this function
 */
function verifyPassword() {
  var xmlHttpRequest = getXMLHttpRequest();
  xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
  xmlHttpRequest.open("POST", "ForAjax", true);
  xmlHttpRequest.setRequestHeader("Content-Type",
      "application/x-www-form-urlencoded");
  xmlHttpRequest.send(null);
}

/*
 * Returns a function that waits for the state change in XMLHttpRequest
 */
function getReadyStateHandler(xmlHttpRequest) {

  // an anonymous function returned
  // it listens to the XMLHttpRequest instance
  return function() {
    if (xmlHttpRequest.readyState == 4) {
      if (xmlHttpRequest.status == 200) {
        document.getElementById("ajaxDiv").innerHTML = xmlHttpRequest.responseText;
      } else {
        alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
      }
    }
  };
}
XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX
servlet class :ForAjax


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

/**
 * Servlet implementation class ForAjax
 */
public class ForAjax extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ForAjax() {
        super();
        // 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
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(" Konzern .... ");
        response.setContentType("text/html");
        response.getWriter().write(" success");
    }

}
 
simple ajax example
           
Thanking you....
for more

Facebook comments