Wednesday, 20 November 2013

Background Form Submission in Servlets

Here is how to submit a HTML form in background without leaving the page. This is a simple example that doesn't make use of the AJAX. I could rather say it as a simple HTML technique.

This is in fact a long lasting dream of mine. While I am satisfied, I ain't completely satisfied. However, this WILL help you if you don't want to submit the form normally or in background with AJAX.

In this example, I've put a simple <iframe> which isn't displayed. When the user clicks on the button, the thing is done in background. But the problem here, is that we don't know the response from the server. We just need to hope that the things are done fine.

I would STRONGLY recommend using AJAX if you would like to know the response from the server. This is the best way. The entire page here is being loaded, but the only thing is that it isn't visible to the user thereby giving him a feel that the form is submitted in the background.

Folder structure




webapps


|


+- bs


|


+- index.html


+- WEB-INF


|


+- web.xml


+- classes


|


+- servlet.java


+- servlet.class


HTML File




<html>


<head>


<title>Background Form Submit</title>


</head>


<body>


<form action="/bs/submit" method="post" target="m">


<input type="text" name="q" size="40"/>


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


</form>


<iframe name="m" style="display:none"/>


</body>


</html>


Here as the target of the submit page is iframe which is not displayed, there is nothing the user can see that a new page is loaded.

web.xml - Deployment descriptor




<web-app>


<servlet>


<servlet-name>myser</servlet-name>


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


</servlet>




<servlet-mapping>


<servlet-name>myser</servlet-name>


<url-pattern>/submit</url-pattern>


</servlet-mapping>


</web-app>



servlet.java - Program to write to a file


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class servlet extends HttpServlet

{

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

{

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



// I am writing it to a file

FileOutputStream fout=new FileOutputStream("out.txt");

fout.write(q.getBytes());

fout.close();

}

}

Note: The file out.txt is written in the Tomcat folder (ex. Tomcat7.0) but not in the project directory. In the next example i'll be telling how to submit form in background using AJAX, so that you get the response from the server too.

Monday, 18 November 2013

Get Global Mouse Pointer Location in Java in One Statement

global mouse location
Here is how to get global mouse pointer location in Java using a single statement. Yes, you heard it right, in a single statement!!

import java.awt.*;
class GetPointerLoc
{
    public static void main(String args[])
    {
    // Get global current cursor location
    Point p=MouseInfo.getPointerInfo().getLocation();
   
    System.out.println(p);
    }
}

getLocation(): This method is present in the java.awt.PointerInfo class. The object for this class can be created using the getPointerInfo() method in the java.awt.MouseInfo class.
Image credit: Iconarchive

Move Mouse Pointer with Arrow Keys in Java

moving mouseYes, you are able to move mouse pointer with arrow keys in Java globally and that is theme of the below program. With the help of this program, the cursor pointer goes up when UP arrow key is pressed, down when down arrow key is pressed.... and press the mouse when enter is pressed. Isn't that cool? Let us take a look at the example below.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MoveCursor extends JFrame
{
Robot r;

    public MoveCursor()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Move Cursor with Keyboard");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // hide the visibility
        setUndecorated(true);
        setOpacity(0f);
        setVisible(true);
       
        // Create Robot object
        try
        {
        r=new Robot();
        }catch(Exception e){}
       
        addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e)
            {
                // If there occured an exception
                // while creating Robot object, r is null
                // then go back
                if(r==null) return;
               
                // Get global current cursor location
                Point p=MouseInfo.getPointerInfo().getLocation();
               
                switch(e.getKeyCode())
                {
                    case KeyEvent.VK_UP: r.mouseMove(p.x,p.y-1); break;
                    case KeyEvent.VK_DOWN: r.mouseMove(p.x,p.y+1); break;
                    case KeyEvent.VK_LEFT: r.mouseMove(p.x-1,p.y); break;
                    case KeyEvent.VK_RIGHT: r.mouseMove(p.x+1,p.y); break;
                    // left click
                    case KeyEvent.VK_ENTER: r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseRelease(MouseEvent.BUTTON1_MASK);
                }
            }
        });
    }
   
    public static void main(String args[])
    {
        new MoveCursor();
    }
}
MouseInfo.getPointerInfo().getLocation(): This method is present in the PointerInfo class whose object can be obtained by getPointerInfo() method in the MouseInfo class. getLocation() returns the current mouse pointer location which is helpful in moving the cursor with arrow keys.

3 JProgressBar and JSlider Examples for a Kickstart

Here are three examples on JProgressBar and JSlider examples that will kickstart your journey. In this tutorial, you will learn:
  1. What is a JProgressBar?
  2. What is a JSlider?
  3. Working with JProgressBar (for beginners)
  4. Coding JProgressBar and Thread class together
  5. Creating JProgressBar using Timer in Swing (Requires to learn event handling)
  6. Working with JSlider (for beginners)

JProgressBar

A JProgressBar is used to display progress of a process. You might have seen it a thousand times, at least. Most commonly, you have seen it in software install wizards and download managers. They show how much process was done.
  1. JProgressBar in Swing Example for Beginners
  2. Coding JProgressBar and Thread together

JSlider

JSlider is used to let the user slide among values. You have seen it in Youtube, while playing a video, you can seek the video where ever you want, the one that you click on to do this is an example of slider.
  1. 4 Ways to create a JSlider in Swing

Ace JTextField, JPasswordField and JFormattedTextField Completely

Here are three complete tutorials on JTextField, JFormattedTextField and JPasswordField that you need to ace to be a better swing programmer.

JTextField

JTextField, as you know, is a component used to write a single line of text. A text field can be seen at this blog's side bar, the subscribe field, where you type your email address.

JPasswordField

JPasswordField is much similar to a JTextField but it allows user to type passwords rather than simple text. You know, your text is visible as it is when you type in your email id, but in the case of password, some round black filled circles are displayed which are used to mask your password, but what you type is the same. This class also gives the option to morph the text with the type of character you want, if you don't like that black spot.

JFormattedTextField

This is a different type of JTextField. This allows user to enter a particular type of data. For example, you can restrict the user to enter only date in it, or a number, or a decimal value ranging between 0.0 and 1.0 etc. Anything else that the user types, will not be accepted. You can better understand this, if you look at the example.

18 Rock Solid Reasons Why You Should Use an IDE

I've been working with an IDE since a couple of years for building my applications. None of my applications were built using Notepad or a similar text editor. There are a quite reasonable amount of reasons which I would like to share why you should use an IDE.

First of all an IDE is an Integrated Development Environment, where you not only write code, but also compile, execute them. It is the only thing you need to complete building an application at the core level, regardless of the testing. The two great IDEs I personally use and of course, most programmers do are NetBeans and Eclipse.

Which one do you use and why?

I use NetBeans to develop desktop applications. I find it easy to create efficient GUI applications in NetBeans because of its simple drag and drop GUI editor which makes my life easy. It doesn't however mean that NetBeans isn't great for building web applications, I haven't built them till date and I don't know how it tastes in it.

I use Eclipse (I changed to Kepler from Indigo recently) to develop web applications. Eclipse is the most popular IDE especially for Java, and there is no doubt in that. Its wide range of plugins often push it to the top of the table.

I first encountered eclipse when researching about Google AppEngine. The tutorials on how to deploy an app to AppEngine frightened me because I have no idea about GIT, pushes and pulls. I thought it would be better if I could do it simply, so did I encounter the Google AppEngine plugin for eclipse.

That's it, with that I've deployed my tiny-apps iGo4iT Search, Google Time and OldSATQ using this eclipse plugin.

Both of the IDEs no doubt are a typical programmer's favorites. But what differentiates them is the environment and the project needs. For programming job seekers, most companies do require to learn at least one IDE.

After a long chat about Eclipse and NetBeans, we need to move forward into the reasons why you are here the ROCK SOLID reasons that you're eagerly waiting for..
  1. Detect compile time errors while writing like semicolon, braces, variable and method declarations etc.
  2. Knowing unknown methods, classes and interfaces. You just need to type a package name followed by a dot (.) and then see the auto complete magic which lists all the sub-packages and classes in it.
  3. Colorful code makes it easy to debug. Who doesn't like colors? When symbols are of one color, keywords are another color, then we can easily detect where a brace is opened, and where it should be closed etc.
  4. IDE notifies if a specific part of code can degrade performance.
  5. Coding convention, smarter way to code: IDE automatically suggests shorter versions of statements we've written.For example, if you write multiple catch blocks, it suggests to replace it with multi-catch specification.
  6. Using external libraries is simple: They're just done in a single click. You don't need to modify classpath settings in your OS. Just clicking on Add Jar and pointing to the library, does it all.
  7. Search for source code: You can search those libraries in the project and see their source code just by typing the classname and hitting enter. In NetBeans, you have it in the top-right corner.
  8. Performance tests can be done in the IDE.
  9. Navigate to errors easily: When there occurs an error or exception in the program, you can navigate to that statement by clicking on the corresponding link in the compile log.
  10. Build GUIs with ease: GUI builders in IDEs need not require the programmer to have knowledge about layouts, the front-end desigining is done by simple drag and drop as said earlier.
  11. Basic code is automatically written: The IDE writes some basic code for you automatically, for example when you put a button on the GUI builder and selected to add an ActionListener for it, then IDE writes an empty handler (actionPerformed) instantly.
  12. Diffing Files allows you to see differences that you've made to the program, its previous versions and other programs as well. This ignites an idea of what went wrong.
  13. Fix imports: Import statements are automatically fixed with a single shortcut (Ctrl+Shift+I in NetBeans) by adding essential ones and removing the unnecessary.
  14. Tab based browsing allows you to move from one program to other easily.
  15. JavaDoc in auto-complete will give you an idea of what you are going to use in the program.
  16. Plugins to deploy applications: You can deploy applications like publishing them to the cloud or wrapping into an exe file etc with simple plugins.
  17. Compiling and executing without command prompt, with simple shortcuts.
  18. Database connections and configurations can be done in the IDE itself without the need of modifying paths in the Environment variables in OS.
Starter programmers need not find any use in the IDEs, but for application development you must learn them and there is no way, you SHOULD use them.

    Store the Largest Number You Can in Java

    Yes, you can store the largest number YOU can think of. So, what is the largest number that came into your mind, right now? Think of adding it, subtracting it, multiplying or at least dividing it with something? I am so curious about this. Aren't you?

    So, let's have some questions, what is the maximum number a long type variable can store? It is 263 - 1, signed. In Java SE 8, for unsigned long it is 264 - 1. Now I do need big numbers than that? Why suspense? You might already have looked into the program, by the time you are reading this? Am I right?

    But wait, let us know at least a bit about the java.math.BigInteger class. One of its constructors takes a String as parameter which I'll use in the program for now. That string can contain the largest number you want, it is on which operations are done. Just as in the String class, operations on BigInteger cannot take place on itself, instead a new BigInteger object is created as a result.


    import java.math.*;
    class BigInt
    {
        public static void main(String args[])
        {
            BigInteger b=new BigInteger("99983938302383039");
          
            // print the value
            System.out.println("The value is "+b);
          
            // To add value
            // A new value is returned but the original
            // isn't modified, just as in String
            System.out.println("Sum "+b.add(new BigInteger("90908977686")));
          
            // To subtract
            // calling big integer - parameter big int
            System.out.println("Difference "+b.subtract(new BigInteger("1000000")));
          
            // To multiply
            // calling * parameter
            System.out.println("Product "+b.multiply(new BigInteger("1000000")));
          
            // To divide
            // calling / parameter
            System.out.println("Division "+b.divide(new BigInteger("10000000000000000")));
          
            // To power, for this time only int, now with BigInteger :(
            System.out.println("Power "+b.pow(10));
        }
    }

    There are still a lot of methods in the BigInteger class that you need to explore. Check out other articles in this blog, there are over 300+, there will at least be 50 which WILL help you in the future.

    Please share this post, if you got what you are here for.