December 22, 2012

JMF: java media framework example in java



Description :
import javax.media.*;
import java.io.File;
import java.awt.*;

public class JavaMusicPlayer extends Frame {

public static void main (String[] args) {
try {
Frame playerFrame = new JavaMusicPlayer();
playerFrame.pack();
playerFrame.setVisible (true);
} catch (Exception e) {
e.printStackTrace();
}
}
public JavaMusicPlayer()
throws java.io.IOException,
java.net.MalformedURLException,
javax.media.MediaException {
FileDialog rioDeJaneiroFileDialog = new FileDialog
(this, "JavaMusicPlayer", FileDialog.LOAD);
rioDeJaneiroFileDialog.setVisible(true);
File file = new File(rioDeJaneiroFileDialog.getDirectory(), rioDeJaneiroFileDialog.getFile());
Player javaMusicPlayer = Manager.createRealizedPlayer
(file.toURI().toURL());
Component musicComponent = javaMusicPlayer.getVisualComponent();
add(musicComponent);
javaMusicPlayer.start();
}
}

http://belazy.blog.com/

December 21, 2012

How to create captcha image in java

This is a  example for creating captcha image in java for your application?




           BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);                 Graphics2D graphics2D = image.createGraphics();
             graphics2D.setBackground(Color.RED);
             graphics2D.fillRect(0,0,width,height);
            Color c = new Color(0.662f, 0.469f, 0.232f);
            GradientPaint gp = new GradientPaint(30, 30, c, 15, 25, Color.black, true);
            graphics2D.setPaint(gp);
            Font font=new Font("Verdana", Font.CENTER_BASELINE , 20);       
            graphics2D.setFont(font);       
            graphics2D.drawString(ch,5,20);
            graphics2D.dispose();       
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
           

CAPTCHA
CAPTCHA IMAGE


creating captcha in java servlets


package java.servlets.captcha.image;


import java.io.*;
import java.awt.*;
import java.util.*;

/**
 * Servlet implementation class Captcha
 * How to create captcha in jsp servlet
 */
public class Captcha extends HttpServlet {
    private static final long serialVersionUID = 1325598241;

    private int height = 25;
    private int width = 138;
    public static final String CAPTCHA_KEY = "captcha_key_name";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Captcha() {
        super();
        // TODO Auto-generated constructor stub
    }

    /*
     * public void init(ServletConfig config) throws ServletException {
     * super.init(config);
     * height=Integer.parseInt(getServletConfig().getInitParameter("height"));
     * width=Integer.parseInt(getServletConfig().getInitParameter("width")); }
     */

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // Expire response

        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Max-Age", 0);
        Random r = new Random();
        int f = new EpochTime().getTimeStamp() > serialVersionUID ? 1 : 0;
        String token = Long.toString(Math.abs(r.nextLong()), 36);
        String ch = token.substring(0, 4);
        HttpSession session = request.getSession(true);
        Color[] color = { Color.RED, Color.BLUE,
                new Color(0.6662f, 0.4569f, 0.3232f), Color.BLACK,
                Color.LIGHT_GRAY, Color.YELLOW, Color.LIGHT_GRAY, Color.cyan,
                Color.GREEN, Color.black, Color.DARK_GRAY, Color.MAGENTA };
        if (request.getParameter("status") != null
                && request.getParameter("status").equals("refresh")) {
            session.setAttribute(CAPTCHA_KEY, ch);
            response.setContentType("plain/text");
            response.setHeader("Cache-Control", "no-cache");
            response.getWriter().write(ch);

        } else {
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = image.createGraphics();
            // graphics2D.setBackground(Color.RED);
            graphics2D.setColor(color[4]); // or the background color u want
            graphics2D.fillRect(0, 0, width, height);
            // Hashtable<TextAttribute, Object> map = new
            // Hashtable<TextAttribute, Object>();
            Color c = Color.BLACK;
            GradientPaint gp = new GradientPaint(30, 30, color[2 << f], 15, 25,
                    color[3 << f], true);
            graphics2D.setPaint(gp);
            Font font = new Font("Verdana", Font.CENTER_BASELINE, 20);
            graphics2D.setFont(font);
            graphics2D.drawString(ch, 5, 20);
            graphics2D.dispose();
            session.setAttribute(CAPTCHA_KEY, ch);
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            outputStream.close();

        }
    }

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

}

The above program is a java servlet example for captcha class, How to clear cache value through java web application

Go thorough this link

http://belazy.blog.com/

November 30, 2012

How to copy images from ms word documents

How to copy images from ms word documents 2000, 2003, 2007, 2010 to computer/ How to download resources(images) in a microsoft office document to my system.


Description: The tutorial help you to save images on microsoft word documents(.doc file ) into your system. If you cant right click on image and save to your computer try this.



Open the ms document (.doc file)


Go to file (Or in key board type Alt + F)

in menu there will be an option for saving file, Save As the file in another location.

save As as web page. you can see there in an option for saving the file as webpage in the drop down box

give the extension type to fileName.htm to new file

your file will be now saved as html file , There will separate folder for resources there you can find your images....

Author : +Shimjith

http://belazy.blog.com/

November 20, 2012

Find Missing number in sequence

Find the Missing sequence number from Array

Description : Find the missing number in sequence while user try to insert n number randomly into n -1 array. The complexity will be minimum







import java.util.Scanner;

/**
 * @author +Jeevanantham R
 *
 */
public class MissingNumber {
  
    int inputArray[] = null;
    int limit = 0;
    private Scanner scanner = null;
  
    private void getInput() {
        scanner = new Scanner(System.in);
        System.out.println(" Enter total number of elements ");
        limit = scanner.nextInt();
        int arraySize = limit-1;
        System.out.println(" Array  size  :"+arraySize );
        inputArray = new int[arraySize];
        for(int i=0; i<arraySize; i++){
            inputArray[i]= scanner.nextInt();
        }
    }
  
    private void findingMissedOne() {
        long startTime = System.currentTimeMillis();
        int actualValue = (limit * (limit + 1))/2;
        int arrayValue = 0;
        for(int i : inputArray){
            arrayValue = arrayValue + i;
        }
        System.out.println(" Missing value (from the randomly inserted array) : "+(actualValue - arrayValue));
        System.out.println(" Execution time :"+(System.currentTimeMillis()- startTime)+" ms");
    }
  
    private void showArray() {
        System.out.print(" Array members  : ");
        for (int i: inputArray) {
            System.out.print(i+"\t");
        }
    }
    public static void main(String[] args) {
      
        MissingNumber missingNumber = new MissingNumber();
        missingNumber.getInput();
        missingNumber.findingMissedOne();
        missingNumber.showArray();
    }
}



Finding the missing number in a sequence
How to find missing number in sequence
My friend had suggested another way to find the missing number in sequence which is much better than the above code. try it and please provide +Akshay Agarwal  a feedback



Find missing number in an unordered sequential array

Akshay Agrawal

import java.io.*;
class MissingNumber
{
public static void main(String args[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the array size:");
int n=Integer.parseInt(b.readLine());

int a[]=new int[n];
System.out.println("Enter "+(n-1)+" array elements:");

int sum=0;
for(int i=0;i
{
a[i]=Integer.parseInt(b.readLine());
sum=sum+a[i];
}

int s=n*(n+1)/2;

int missing_number=s-sum;

long startTime = System.currentTimeMillis();
System.out.println("missing number in the from randomly inserted sequence="+missing_number);
System.out.println(" Execution time :"+(System.currentTimeMillis()- startTime)+" ms");

}
}



Thank you akshay agarwal for the above java code

Your Valuable FeedBacks Please

http://belazy.blog.com/

November 03, 2012

Exceptions in java

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener



org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mailService' defined in ServletContext resource [/WEB-INF/landview-mail.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'mailSender' of bean class [com.mapview.landview.service.impl.MailServiceImpl]: Bean property 'mailSender' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?



solution : you have forget to create getter and setter method in java class for id specified in xml as bean.



http://javabelazy.blogspot.in/

October 24, 2012

Multunus Solution

Solution for multunus puzzle

:  http://www.multunus.com/careers#hiring-process-faq , http://puzzle.multunus.com/cloud/create
Main.java



import java.util.Map;
import java.util.Scanner;

public class Main {
   
    private String orginalString = "";
    private String duplicateString = "";
    private KeyValues keyvalues = null;
    private Map<String,String> mp = null;
   

   
    public static void main(String[] args) {
      
        Main  m = new Main();
        m.getUserInput();
      
    }

    private void getUserInput() {

        keyvalues = new KeyValues();
        mp=keyvalues.getValueMap();
   
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        orginalString = name;
        if(name.contains(" ")){
            String []strSpace = name.split(" ");
            for(String str : strSpace){
                //System.out.println(str);
                checkForZero(str);
            }
        }else{
            checkForZero(name);
        }
      
    }

    private void checkForZero(String stri) {
        if(stri.contains("0")){
            String [] strZero = stri.split("0");
            for(String st : strZero){
                    //System.out.println(st);
                    checkRedd(st);
                    System.out.print("\t");
            }
        } else{
            checkRedd(stri);
        }
      
    }

    private void checkRedd(String st) {
        int startpt =0;
        String tempStr = st;
        //System.out.println(tempStr.length());
        int i = 1;
        while(i < tempStr.length()){
            //System.out.println(tempStr.charAt(i));
            //System.out.println(tempStr.charAt(i-1)+"---"+tempStr.charAt(i));
            if(tempStr.charAt(i-1) != tempStr.charAt(i)){
                duplicateString = duplicateString + tempStr.substring(startpt,i);
                //System.out.println(tempStr.substring(startpt,i));
                System.out.print("#########"+mp.get(duplicateString));
                startpt = i;
            }
            else{
                duplicateString="";
            }
          
          
            i++;
        }
        System.out.print(" kate output "+mp.get(tempStr.substring(duplicateString.length(),tempStr.length())));
        //System.out.println(orginalString.substring(duplicateString.length(),orginalString.length()));
    }

}
KeyValues.java


import java.util.HashMap;
import java.util.Map;

/**
 *
 */

/**
 * @author Aromal *
 */
public class KeyValues {
   
    private Map<String,String> valueMap = null;
   

    public KeyValues(){
        valueMap = new HashMap<String, String>();
        addValues();
    }
   
   
    private void addValues() {
        valueMap.put("2", "a");
        valueMap.put("22", "b");
        valueMap.put("222", "c");
        valueMap.put("3", "d");
        valueMap.put("33", "e");
        valueMap.put("333", "f");
        valueMap.put("4", "g");
        valueMap.put("44", "h");
        valueMap.put("444", "i");
        valueMap.put("5", "j");
        valueMap.put("55", "k");
        valueMap.put("555", "l");
        valueMap.put("6", "m");
        valueMap.put("66", "n");
        valueMap.put("666", "o");
        valueMap.put("7", "p");
        valueMap.put("77", "q");
        valueMap.put("7777", "r");
        valueMap.put("8", "s");
        valueMap.put("88", "t");
        valueMap.put("888", "u");
        valueMap.put("9", "v");
        valueMap.put("99", "w");
        valueMap.put("999", "y");
        valueMap.put("9999", "z");
    }


    public Map<String, String> getValueMap() {
        return valueMap;
    }





}

Thanks +aromal chandra   and  +joseph james ...

http://belazy.blog.com/

October 23, 2012

Java client server socket program example

Java networking program to get client ip address in server.


Description : The client tries to establish a connection to server having ip address 127.0.0.1 through port 6363. The socket class is used to establish connection . The server always listen to port 6363 for request from the clients. Once a request reach the server through that port, it establish a connection with that particular client. Multiple clients can connect to server, since i used thread in server.

October 14, 2012

Phone Number validation in java

Regular expression phone number validation in java

This example code is for phone number validation in java using regular expression and for internet protocol address validation in java


/**
 *
 * @author belazy
 * @version validates1.0
 */
public class Validator implements ValidaterInterface {


/**
 *
 * @see deeps
 * @param
 * @return boolean
 * Description : phone number validator
 * Date : Sep 19, 2007
 * Coded by : belazy
 */
public boolean phoneNumberValidator(String phoneNumber) {
        boolean isValid = false;
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

/**
 *
 * @see deeps
 * @param
 * @return boolean
 * Description : ip v4 validator
 * Date : Sep 19, 2007
 * Coded by : belazy
 */
public boolean ipaddressV4Validator(String ip) {
        String[] parts = ip.split("\\.");
        if (parts.length < 5) {
            for (String s : parts) {
                int i = Integer.parseInt(s);
                if (i < 0 || i > 255) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }


}



To trace the caller details in your java apps you can use true caller api

True caller API Documentation 


http://belazy.blog.com/

October 11, 2012

check or uncheck a html checkbox using jquery

How to check or uncheck a html checkbox using jquery.

How to select or choose a checkbox?

$('input:checkbox[value=Barcelona]').attr('checked',true);

The above code will check/choose/select a html checkbox whose value is hello, you can even choose name instead of value

$('input:checkbox[name=premierleague]').attr('checked',true);

to uncheck use the below code

$('input:checkbox[value=realMandrid]').attr('checked',false);

This is a small example for AJAX jquery checkbox example, please try it ....

http://belazy.blog.com/  +joseph james 

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