Wednesday, 27 November 2013

One Point about For Each Loop I Ridiculously Forgot

Laughing at me! ;)
Laughing at me! ;)
It is very shameful that I forgot this simple point and had written a post on for-each loop previously.The point is that for-each loop can be used to iterate through an iterator. See this snippet..

ArrayList<String> as=new ArrayList<String>();

as.add("Item 1");

as.add("Item 2");

as.add("Item 3");

as.add("Item 4");

for(String st:as){

System.out.println(st);

}

It is not just for an ArrayList but for any iterator.
In fact, for each loop is designed for this. But I forgot that. I apologize for the readers that I had missed that most-important point in that post. I thought of updating it, but I need to show off my mistake, so did I write this post. Also take a look at what oracle has written about for-each loop.

Photo credit: Wikimedia

Autocomplete HTML Input Field using JSP and JQuery in Five Lines!


Everyone is fascinated about auto-complete. Right? I think, Are you? Drop in the comment below. Long time I've been connecting JQuery and Java and have some of the posts like loading JSP file in JQuery in one line Now, it is time to go further.

I would be blogging now a simple example on how to connect auto-complete for a HTML text field to a JSP file with JQuery in one line! Yes, in five lines!, YOU heard it RIGHT!

Project structure

Folder path: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_autocomplete



jq_autocomplete

                |

                +-- index.html

                +-- auto.jsp

index.html - HTML file



<html>
    <head>
        <title>Send POST Request to Servlet with JQuery</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
                // When any key is down
                $(document).keydown(function(){

                    // Get the input element and its value
                    var i=$("#com");
                    var val=i.val();

                    // Send request only if user types alphabet
                    // because auto.jsp returns names of companies
                    // which contains only alphabets
                    if(val.match(/^[A-z]+$/))
                    {
                        // Send request and get the data
                        $.get("auto.jsp?com="+val,function(data){

                            // Get each item separated by new line
                            var items=data.split("\n");

                            // put those items in autocomplete! That's it!
                            i.autocomplete({source:items});
                        });
                    }
                   
                });
        </script>
    </head>
   
    <body>
        <input type="text" id="com" name="com"/>
    </body>
</html>

The point here is that the function keydown is executed every time when a key is down in the document and so the request will be sent each time when the key is down degrading performance of the application. To avoid this, the if-condition is useful which checks if the value matches the regex which corresponds to any alphabet.

auto.jsp - Returns auto complete data



<%@page import="java.util.*"%>
<%
    // Create ArrayList and add some items
    ArrayList<String> as=new ArrayList<String>();
    as.add("Google");
    as.add("Yahoo");
    as.add("Apple");
    as.add("Microsoft");
    as.add("Linkedin");
    as.add("Facebook");
    as.add("IBM");
    as.add("Oracle");
    as.add("Salesforce");
    as.add("Amazon");
   
        String s=request.getParameter("com");
       
            for(String st:as)
            {
                if(st.toLowerCase().startsWith(s.toLowerCase()))
                {
                    out.println(st);
                }
            }
%>

The best price you could pay for this post is sharing it. I thank you in advance :)
Photo Credit: Angelina :) via Compfight cc

Monday, 25 November 2013

Send POST Request to Servlet in JQuery in One Statement!

Post request with JQuery
Here is a single-line statement to send a POST request to a servlet with JQuery. This is gonna be dead simple. Yes, so simple that it is nothing more than a JQuery method call. Curious about what the method is? Me too! It is none other than..

post(): There are a lot of versions of this method. But here, we are going to use the simple version which takes the url-pattern and the data to be submitted.

Project structure

Folder: D:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_post


jq_post
        |
        +-- index.html
        +-- WEB-INF
                    +-- classes
                            +-- simple.java
                            +-- simple.class

index.html


<html>
    <head>
        <title>Send POST Request to Servlet with JQuery</title>
        <script src="http://code.jquery.com/jquery-2.0.0.js"></script>
        <script>
            $(function(){
           
            $( "#hform" ).submit(function(event) {
           
                // Stop form from submitting normally
                event.preventDefault();
               
                // Get some values from elements on the page:
                var form = $(this);
               
                // Get the value in input uname
                term=$("input[name='uname']").val();
               
                // Send the data using post
                var posting = $.post("hello",{uname:term});
               
                    // When the POST request is done..
                    // data: The output printed in servlet
                    posting.done(function(data) {
                       
                        // Put the results in a div
                        $("#view").append(data+"<br/>");
                       
                    });
            });
            });
        </script>
    </head>
   
    <body>
   
        <!--Create the form-->
        <form id="hform" action="/jq_post/hello" method="post">
            <input type="text" name="uname"/>
            <input type="submit" value="SUBMIT"/>
        </form>
        <!--Create the form-->
       
        <div id="view"/>
    </body>
   
</html>

web.xml - Deployment descriptor



<web-app>
    <servlet>
        <servlet-name>ser</servlet-name>
        <servlet-class>simple</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>ser</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Related: What is web.xml in servlets?

simple.java contains doPost()



import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class simple extends HttpServlet
{
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
        // Get the user name from html input field
        String name=req.getParameter("uname");
       
        // Get PrintWriter obj using getWriter() in HttpServletResponse
        PrintWriter pw=res.getWriter();
       
        // Print, that's it!!
        pw.println("Hello "+name+"!");
    }
}

Image credit: tuicool.com

Saturday, 23 November 2013

Compile and Run Java Programs in One Click!

Here is how we can compile and run Java programs in one click. Yes, you heard it right and that is absolutely true. What about commands? Do i need to write them. Of course, you need them, but you don't need them to type always.

Creating a batch file lets you do this. In this post you'll learn how to compile all Java programs, wait till the output is seen, hide the echo as well!

Before we start, let us talk a bit about the batch files.
  1. They are the files which contains a set of commands that are executed in the command prompt one by one.
  2. They are saved with a .bat extension.
  3. Whenever you click on that file, those commands are executed one after the other.
So, it is clear that you need to write the two commands that compile and execute your program. They are javac MyProgram.java and
java MyProgram
OK. That's it? Can we just include these two lines and save the batch file? Hmm, but you can't see the output, unless it is a GUI program. Because, the output is printed and the command prompt is closed. That's it. Now, is there a solution? Yes, here it is.

Pause batch file to display output


@echo off
javac MyProgram.java
java MyProgram
pause

The pause command stops the command prompt from exiting.
The @echo off command doesn't display the path of the directory in the command prompt. For instance, if you are executing this in the folder E:\java then E:\java> is not visible. Just see it in practice for a clear understand.

Though there are any errors, then the second command is executed. The program will run depending upon the previous class file (if any). Otherwise, could not find or load main class MyProgram error will be displayed.
To prevent this, you can delete the previous class file and that command should be placed before.

Stop executing previous class file code [Use with caution]


@echo off

del MyProgram.class

javac MyProgram.java

java MyProgram

pause

I recommend you to use this with caution, once the previous class file is deleted, you might not get back your code. Your program stays fine, but it is a modified version that contains errors.

One last tip, to compile all the classes, use javac *.java

@echo off

javac *.java

pause
However, you cannot execute all programs at a time. You'll need to write one by one.

Writing and saving them?

Simple,
  1. Write those commands in notepad and save them in the directory where your Java programs are present.
  2. Click on that batch file, every time you write it!
  3. To make your life more easy, just create a shortcut for that batch file on your desktop
and here we go, click it every time to compile and run!

If you like this post, please share it, it would be the highest price you could pay for this post.

Image credit: logopond.com

Load a JSP File using JQuery in One Line


Here is how to load a JSP file using JQuery in a single line!. The following is a hello world JSP example which will be loaded on a button click using the JQuery. As you can see from the image, the paradigm, write less, do more. is exactly exemplified here.

Project structure

Folder: C:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_jsp

jq_jsp

    |

    +-- index.html

    +-- hello.jsp


index.html




<html>


<head>


<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


<script>


// When the document is ready..


$(document).ready(function(){


// When any element with input tag is clicked


// execute the following function


$("input").click(function(){


// Get object of element with loadHere id


// And in it load the hello.jsp file!


$("#loadHere").load("hello.jsp");


});


});


</script>


<title>Load a JSP File in JQuery</title>


</head>




<body>


<input type="button" value="Get hello"/>


<div id="loadHere"/>


</body>


</html>


hello.jsp




<%


response.getWriter().println("Hello world!");


%>


The greatest appreciation you could give me is sharing this article. I would sincerely appreciate it :)

Friday, 22 November 2013

Submit a Form to Servlet using JQuery

Here is how to submit a form in background to servlet using JQuery in one single line. The scope of the program is to print a hello message in a html div. Note that you need to have a basic knowledge of JQuery and Javascript to understand this. But I'm pretty sure that the helpful commentaries will give you an understanding even if it is your first sight :)

Folder structure

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\jqform

Project structure



jqform


|


+-- index.html


+-- WEB-INF


+-- web.xml


+-- classes


+-- simple.java


+-- simple.class


HTML Files

index.html




<html>


<head>


<title>JQuery - Servlet form submission</title>


<!--To use jquery, loading this is mandatory-->


<!--If you don't have internet connection, download this file


and give the local path


-->


<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>


<script>


// When the page is loaded, then..


// execute this function


$(document).ready(function(){




// When the button with id submit


// is clicked, this function should


// be executed


$("#submit").click(function(){


// Get the value in the val field


var val=document.getElementById("t").value;




// Now, get the element with id displayMsg


// and in it load the given file


// The text printed in the servlet class now


// comes in the displayMsg div


$("#displayMsg").load("/jqform/go?q="+val);


});


});


</script>


</head>




<body>


<input type="text" name="q" id="t"/>


<input type="button" id="submit" value="SUBMIT"/>


<div id="displayMsg"/>


</body>




</html>


Here, the load() method takes a string which corresponds to the page that is to be loaded. Here, we are indirectly calling the page http://localhost:8080/jqform/go?q=gowtham (when you type 'gowtham' in the input field) and that the content in the page is pasted in the displayMsg division. In other words, simply, the above page is loaded in the div instead of a new page. That's it.

Deployment Descriptor

web.xml




<web-app>


<servlet>


<servlet-name>puppy</servlet-name>


<servlet-class>simple</servlet-class>


</servlet>




<servlet-mapping>


<servlet-name>puppy</servlet-name>


<url-pattern>/go</url-pattern>


</servlet-mapping>




</web-app>


Servlet Programs

simple.java




import javax.servlet.*;


import javax.servlet.http.*;


import java.io.*;


public class simple extends HttpServlet


{


public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException


{


String q=req.getParameter("q");




// Get write object and print


PrintWriter pw=res.getWriter();


pw.println("Hello "+q);


}


}


Thursday, 21 November 2013

Set Notepad Icon for JFrame in Swing

Here is how to set notepad icon for JFrame in Swing. Yes, you heard it right. But is it simple. Dead simple. Just see it below.

import javax.swing.*;

import java.awt.*;

import java.io.*;

import javax.swing.filechooser.*;

class WindowsIconForJFrame extends JFrame

{

public WindowsIconForJFrame()

{

createAndShowGUI();

}



private void createAndShowGUI()

{

setTitle("Windows Icon");

setDefaultCloseOperation(EXIT_ON_CLOSE);



ImageIcon i=(ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(new File(System.getenv("windir")+"\\notepad.exe"));

setIconImage(i.getImage());



setSize(400,400);

setVisible(true);

setLocationRelativeTo(null);

}



public static void main(String args[])

{

new WindowsIconForJFrame();

}

}

FileSystemView.getFileSystemView(): This method gets the FileSystemView object which contains the getSystemIcon() method which takes java.io.File as parameter. The file object is corresponded to the notepad.exe. To work with this program, make sure that you have notepad in your system.

setIconImage(i.getImage()): This method takes java.awt.Image which can be obtained using getImage() in javax.swing.ImageIcon class.

Notepad icon for JFrame

Related: How to set default system icons for JFileChooser?