Showing posts with label How to. Show all posts

How to apply/set up swing look and feel?

Swing application allows us to change the Look and Feel of the frame and its internal components as well. UIManager.setLookAndFeel() method used with different arguments to change its look.

Swing look and feel

We'll achieve blow swing Look and Feel
  • Metal - javax.swing.plaf.metal.MetalLookAndFeel
  • Nimbus -
  • CDE/Motif -
  • Windows -
  • Windows Classic -

To achieve Look and Feel add the code before it get visible. You have to copy just try-catch block in below code. If you set look and feel to parent Jframe. It also affect look to the children (calling other frame). Check the below code snippet. You have to uncomment the line for your desired look.
public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                /* It represent the frame border as internal jframe.
                 * However it only works with metal look and feel.
                try {
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                new LookAndFeel().setVisible(true);

Understanding basics java.awt.Desktop

I was finding some good topic to write an article. So looking all around my projects. I used java.awt.Desktop class in my program. Lets discuss all about the Desktop class of java.

What is java.awt.Desktop?
          java.awt.Desktop class designed to interact with system programs. It executes the system command to handle the operation of file and sometime URL(s). So now lets take a look at the methods of Desktop class. All methods throws IOException so use try-catch.

Desktop.getDesktop().browse(URI uri)
This function is used to open URL Uniform (or universal) Resource Locator. This will open the URL in system's default web browser client.

Desktop.getDesktop().edit(File file)
It'll open file specified in parameter with system related editor. Say your file is .txt, .docx, etc... Be careful with this because if there ain't any editor related to that file type it'll throws error Failed to edit file:/c:/1.pdf. Error message: Unspecified error. I'm trying to edit .pdf file which is not supported by my system.
Desktop.getDesktop().edit(new File("c:\\1.txt"));

Desktop.getDesktop().isSupported(Action action)
This method designed to check that system user has enough privileges to do operation. System admin can set  file open, edit, print, browse and mail permission of other users. It'll return true and false based on permission.

It'll open the default mail client program of system.

Desktop.getDesktop().mail(URI uri)
Helps to set email, subject, message, cc and bcc on system default mail client. Predefined subject of mail and To so user don't need to remember your mail id or support mail id.
// To set space use "%20"

Desktop.getDesktop().open(File file)
Open the specified file in system's default program.
Desktop.getDesktop().open(new File("c:\\1.pdf"));

Desktop.getDesktop().print(File file)
Print the specified file in system's default printer.
Desktop.getDesktop().print(new File("c:\\1.pdf"));

Tests whether this class is supported on the current platform. If it's supported, use Desktop.getDesktop() to retrieve an instance.

How to get Latitude - Longitude without GPS in mobile device?


What is GPS?
GPS stands for Global Positioning System. Its a hardware used to get the accurate location of device. It gives the Latitude - Longitude of the device.

What if there ain't GPS?
You might used Google Maps in non GPS device. They are still able to get the perfect location of your device. So we'll look into that situation how they target the mobile device. All you need is get below details from mobile device.

1. Mobile Country Code (MCC) - To detect current country of device.
2. Mobile Network Code (MNC)- Te delete current service provide.
3. Local Area Code (LAC)- To detect device in which region.
4. Cell ID - Unique id of that region.

I created GeoLocation class in javaQuery API 8.1 . I'm using free service to get the latitude and longitude. Sometime you may get 0.0 for Latitude and Longitude. It says that there is no record available for that details. This API is for testing purpose. If you are creating the paid application or Official application, buy service to get the latitude and longitude using mcc, mnc, lac and cellid. Let's take a look at code snippet.
 * MAPTargetByMobile(int, int, int, int);
 * MAPTargetByMobile(mcc, mnc, lac, cellid);
 * It'll only give you Latitude and Longitude
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;

public class Demo {
    public static void main(String[] args) throws IOException{
        GeoLocation Target = javaQueryBundle.createGeoLocation();
        Target.MAPTargetByMobile(404, 58, 1339, 9029);
Now what next? 
Use Google Maps to get location of mobile device using Latitude and Longitude.

Related Article:
How to create mobile tracking application? []

How to download file with Progress bar in Android?

Today in this tutorial I'm going to demonstrate the file download example in Android. I've Googled everything about it. There are examples available on the Internet. However you'll find some difficulties when you integrate in your code. So lets see how they implemented...

Source Code (
ContextBean used to access application context in any class.
import android.content.Context;
 * This will help you to use application context in any file with in project.
public final class ContextBean {
  private static Context localContext;
  public static Context getLocalContext() {
        return localContext;
  public static void setLocalContext(Context localContext) {
        ContextBean.localContext = localContext;

Source Code (MainActivity Class)
//In your main activity file.
protected void onCreate(Bundle savedInstanceState) {

Source Code (

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;

public final class DownloadFile extends AsyncTask {
      // Progress Dialog
      private ProgressDialog pDialog;
       // Progress dialog type (0 - for Horizontal progress bar)
       public static final int progress_bar_type = 0;
       private Activity mainActivity = null;
       private Context mainContext = null;

       public DownloadFile(Activity a,Context c){
        this.mainActivity = a;
        this.mainContext = c;
        pDialog = new ProgressDialog(mainContext);
       protected void onPreExecute() {
        pDialog.setMessage("Downloading file. Please wait...");
       protected String doInBackground(String... params) {
              int count;
              try {
               URL url = new URL(params[0]);
               URLConnection conection = url.openConnection();
               // this will be useful so that you can show a typical 0-100%
               int lenghtOfFile = conection.getContentLength();
               // download the file
               InputStream input = new BufferedInputStream(url.openStream(),8192);
               /* Output stream
                * Folder path :
               String dataDirPath = ContextBean.getLocalContext().getPackageManager().getPackageInfo(
                 ContextBean.getLocalContext().getPackageName(), 0).applicationInfo.dataDir;
               OutputStream output = new FileOutputStream(dataDirPath);
               byte data[] = new byte[1024];
               long total = 0;
               while ((count = != -1) {
                      total += count;
                      // publishing the progress....
                      // After this onProgressUpdate will be called
                      publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                      // writing data to file
                     output.write(data, 0, count);
              } catch (Exception e) {
               Log.w("Your_Tag","Download Error", e);
        return null;
        * Updating progress bar
        * */
       protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        * After completing background task Dismiss the progress dialog
        * **/
       protected void onPostExecute(String file_url) {
              // dismiss the dialog after the file was downloaded
              AlertDialog alertDialog = new AlertDialog.Builder(mainActivity).create();
              // Setting Dialog Title
              alertDialog.setTitle("Title of Box");
              // Setting Dialog Message
              alertDialog.setMessage("Download Complete");
              // Setting OK Button
              alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog,
                 final int which) {
              // Showing Alert Message

Now let see how you can access the class. You can use this class with on click event , Menu item click event, etc... It depends on you how you want to access. I'm accessing this class in Main Activity with
protected void onCreate(Bundle savedInstanceState) {...}
 * You have to pass Activity and Context of the application to class
 * this : Activity (1st)
 * this : Context (2nd)
DownloadFile objDownloadFile = new DownloadDatabase(this, this);
Sometime you may got the exception Cannot execute task : the task has already been executed. Its because if you are dealing with AsyncTask . Its one time use class with one Object/Instance.

Create new object every time if you want to use more than one time.

Ad Tracking: The Invisible Spy

In daily life we spent hours on the Internet. Have you ever wonder that why there's an advertise of website that you opened a minute(s) ago.

Ad Traking

For an Example: When you want to buy something, you open random website(s). You check out price, color, size and all. For a obvious reason you don't buy the things. Minute you open the next news website or some blog you'll get the advertise of the same website you tried to purchase. That is called Ad Tracking.

Why is so?: Only some natural resources are free on the Planet Earth. Everyone wants to make money. They put advertise(s) on their website, blog. When you click on it, advertising company pay money to owner of that website for serving advertise.

Lets have a look on How Ad Tacking works.

Ad Traking

This article is posted on the request of reader as guest posting.
Image Courtesy :

Guest Author:
Allison Morris 

JTable (javax.swing.JTable) basics explained

Importance of Jtable in Desktop application.
If you are beginner then you must know why and how to use JTable. Table really important component of all programming language. Whether you work around web application, desktop application or consider database.

             Jtable helps you to organize your data in proper manner. Let say you want to show all your employee's details. Jtable is your option.

Today's agenda for JTable
  • How to change width of column in JTable?
  • How to change height of cell in JTable?
  • How to disable column in JTable?
  • How to disable row in JTable?

How to change width of column in JTable?

How to change height of cell in JTable?
private void updateRowHeights() {
   try {
        for (int row = 0; row < jTable1.getRowCount(); row++) {
            int rowHeight = jTable1.getRowHeight();
            for (int column = 0; column < jTable1.getColumnCount(); column++) {
               Component comp = jTable1.prepareRenderer(jTable1.getCellRenderer(row, column), row, column);
               rowHeight = Math.max(rowHeight, comp.getPreferredSize().height + 20);
               //Change the rowHeight in above line
          jTable1.setRowHeight(row, rowHeight);
   } catch (ClassCastException e) {

How to disable column in JTable? , How to disable row in JTable?
Object[][] rowData = new Object[10][2];
        Object columnNames[] = {"Column 1", "Column 2"};
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames) {
            public boolean isCellEditable(int row, int column) {
                if (column == 1 || row == 5 || row == 10) {
                    return false;//the nth row, column is not editable  
                return true;

Other article related to JTable :
How to update jtable dynamically from Oracle , MySQL (Database)?
How to implement JButton in JTable?
How to implement JComboBox in JTable?

How to implement JButton in JTable?

I was working on Inventory management project where i have to place button on jTable that shows order. I googled and found solution but he didn't provided proper information with all code. I'm gonna explain it properly with all basic code.

jTable, jButton
jTable - jButton

Source :
Download :
                      - Download the class file and place it in proper package. Don't forget to include your package in starting of code.

String[] InvoiceArray = new String[20];
//Declare above variable globally. Used by two-three methods. Change variable name as per your need.

 * import the ButtonColumn class if you are not working in IDE
 * I used formWindowOpened event to load content in Jtable but you can use other event.
 * All you need is put the code with in that event.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[4][2]; // 4: is number of row ; 2: is number of column
        Object columnNames[] = {"Invoice No", "View Report"}; // Name of columns
        for (int i = 0; i < 4; i++) {
            InvoiceArray[i] = i + "-2345";
            rowData[i][0] = i + "-2345";
            rowData[i][1] = "View Order " + i; // Can change the text of button.
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
        ButtonColumn buttonColumn = new ButtonColumn(jTable1, showOrder, 1); // 1: is column number. column count starts with 0,1,2...

Now lets have a look on code snippet to handle the button click event. We find the button row index onclick and get the value from InvoiceArray by matching index.

Action showOrder = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
       //JTable table = (JTable) e.getSource(); // If you have multiple component following the ActionEvent
            int modelRow = Integer.valueOf(e.getActionCommand());
            if (InvoiceArray[modelRow] != null) {
                /* We are placing invoice no in array 
                 * And track the button click index
                 * And fetch index in invoice no
                System.out.println("Your Invoice No:" + InvoiceArray[modelRow]);
            } else {
                JOptionPane.showMessageDialog(rootPane, "No records found!");

How to implement JComboBox in JTable?

JTable and ComboBox
JTable and ComboBox
Its very tough for beginner to implement JComboBox with in JTable. I thought let me explain this example with all basic requirement one require. We're going to perform the below operations on JComboBox.

  • Implement JComboBox in JTable.
  • JComboBox value from Database.
  • Database index of the selected JComboBox.

So lets not waste time and take a look at the code. First of all you'll have to decide when the JTable update its model or say it's data. I used formWindowOpened event to load data in JTable.

private JComboBox comboBox;
//Above variable declared globally.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[5][1];
        Object columnNames[] = {"Name of Item"};
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
         * Below method creates the JComboBox in JTable. Check the method code below.
         * jTable1.getColumnModel().getColumn(0) : set the column index as per your need.
private void setItemNameColumn(TableColumn itemColumn) {
        comboBox = new JComboBox();
        try {
            Connection con = variables.getDatabaseConnection();
            PreparedStatement item_stmt = con.prepareStatement("select idwarehouse,NameOfProduct from warehouse;");
            ResultSet item_rs = item_stmt.executeQuery();
            while ( {
                comboBox.addItem(new Item(item_rs.getInt("idwarehouse"), item_rs.getString("NameOfProduct")));
               // Bind Name of product and index in ComboBox
        } catch (Exception e) {
        comboBox.addActionListener(this); // Set action listener 
        itemColumn.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");

// Bean for ComboBox
public class Item {
        private int id;
        private String description;
        public Item(int id, String description) {
   = id;
            this.description = description;
        public int getId() {
            return id;
        public String getDescription() {
            return description;
        public String toString() {
            return description;
// Action listner that read the selected index every time and shows database index.
public void actionPerformed(ActionEvent e) {
   if (e.getSource().equals(comboBox)) {
         comboBox = (JComboBox) e.getSource();
         Item item = (Item) comboBox.getSelectedItem();
              System.out.println("Database Index:"+item.getId());
That's it. All you need to put all code in your project. If you have any problem comment here. 

How to bind images - icon in .jar file?

                        This is really easy task however its seems hard for beginners. You can bind *.jpg, *.png, *.gif in .jar file. I didn't try other file types. If some other file type is working comment it in the article. Anyways this comes in picture when you are dealing with Graphical User Interface (GUI) application. All you need to put images, icons, etc... in your project.

Hoping you are using package phenomenon in your project. It shows neat and clean programming style. It'll help you and other team member to find proper class in proper package. Below is the image of my test project for javaquery.

Java Project Structure

I used com.javaquery.images package to place all my required images. Lets roll for the code... 

How to set button, menu item, label, frame image in netbeans?

Step 1: Store image in proper package.
Step 2: [If required: Goto Windows > Properties . It'll show properties of object in sidebar.] Select object and go to icon properties.

Step 3: Click on browse. Select image from proper package.

How to set image in non IDE code?
 IDE handles the basic properties of object but if you are working on some other editor that don't provide check the below code to set the image for that object.

// jButton1 is my object so change it to yours and also change the path of image in getResource("path_to_image");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Redo.gif")));

Subscribe on social media for more stuffs.
Related Articles:
[How to create .jar file in netbeans? :]
[How to Open file by double clicking on it in our .jar file? :]
[How to get .java file from .class file? :]

Understanding basics of jTabbedPane

This tutorial for beginners. I'll help you to understand the basics of jTabbedPane. We'll understand the below topics in this tutorial.

  • How to add new tab in jTabbedPane? or How to add new tab in java swing?
  • How to remove tab from jTabbedPane? or How to remove tab in java swing?
  • How to set popup menu in jTabbedPane? or How to set icon in popup menu item?

jTabbedPane , swing

If you are working with IDE like netbeans then it provides drag and drop facilities for components. All you need to implement code for new tab. Lets have a look at code snippet.
 * New Tab 
 * Code for non IDE environment 
JTabbedPane jTabbedPane1 = new JTabbedPane();
JPanel content = new JPanel();
content.setLayout(new BorderLayout());

 * Code for IDE environment and non IDE enviroment 
 * Add this line of code for button click event, key stroke event, etc...
 * Below code insert jTextArea in every new tab. You can insert component as per your need.
 * jTabbedPane1.addTab("Untitled",new JScrollPane(new JTextArea());
jTabbedPane1.addTab("Untitled", new JScrollPane());

Now lets check out the code for closing the tab. I think there no need to say that jTabbedPane must be initialized.
 * Remove tab / Close tab
 * Add this line of code for button click event, key stroke event, etc... 
int remIndex = jTabbedPane1.getSelectedIndex();
if (remIndex < 0) {
     JOptionPane.showMessageDialog(rootPane, "No tab available to close");
} else {

Let's create popup menu on the tab. I'm giving you the basic idea for creating popup menu. You need to implement click event for that popup menu items. In below code snippet you can also find how to set icon in popup menuitems.

How to implement click event on popup menuitems?
- You can attach action listener for that menu items.
  * Popup menu
  * images/icons for popup menuitems are available in package com.javaquery.images
  * Add this code in constructor 
 JPopupMenu pop_up = new JPopupMenu();
 JMenuItem savefile = new JMenuItem("Save");
 savefile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Save.gif")));
 JMenuItem openfile = new JMenuItem("Open File");
 openfile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Open.gif")));
 JMenuItem newtab = new JMenuItem("New Tab");
 JMenuItem closetab = new JMenuItem("Close Tab");

 //savefile.setAccelerator(KeyStroke.getKeyStroke("control S")); //Key stroke
 //savefile.addActionListener(new savefile()); //new savefile() is class the implements actionlistner


How to implement Cut, Copy, Paste, Undo, Redo in java swing?

I was exploring the folders and found my college project. I thought let me write article for old school project. It might help students working for first time in java swing. Its very easy to implement Cut, Copy, Paste, Undo, Redo when you deal with text input(s).

Cut, Copy, Paste, Undo, Redo in java swing

I took jTextarea in this example. I'll give you core script but you have to modify the code as per your need. Like onclick event, KeyStroke, etc...

Code for handling cut event
 /* Below code for netbeans */ 
 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

 /* Below code when you want to attach action listener */
 class cut implements ActionListener {
        public void actionPerformed(ActionEvent e) {

Code for handling copy event
 /* Below code for netbeans */ 
 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

 /* Below code when you want to attach action listener */
 class copy implements ActionListener {
        public void actionPerformed(ActionEvent e) {

Code for handling paste event
 /* Below code for netbeans */ 
 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

 /* Below code when you want to attach action listener */
 class paste implements ActionListener {
        public void actionPerformed(ActionEvent e) {

To implement Undo and Redo you have to run code with in constructor. Below code will implement UndoableEditListener for jTextarea.
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager;

/* Create global variable */
UndoManager undo = new UndoManager();

                new UndoableEditListener() {
                    public void undoableEditHappened(UndoableEditEvent e) {

Code for handling undo event
 /* Below code for netbeans */ 
 private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
        } catch (CannotRedoException cre) {

 /* Below code when you want to attach action listener */
 class undo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
            } catch (CannotRedoException cre) {

Code for handling redo event
 /* Below code for netbeans */ 
 private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
        } catch (CannotRedoException cre) {

 /* Below code when you want to attach action listener */
 class redo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
            } catch (CannotRedoException cre) {

Source Code

How to setup cookie free or cookie less sub domain in java?

Before we start tutorial about creating cookie free or cookie less domain in java. You'll need to setup sub domain. To setup sub domain in java + tomcat7 read the article :

Why should i create cookie free or cookie less sub domain for static content? 
    Below image helps you to understand the real time scenario. Lets say you set your cookie's domain "". Browser use this cookies when you request content from and creates network traffic. Read more about cookie free domain :

Solution: To get over this problem you must set domain of cookie like .We can forcefully insert www in URL. If URL contains www then cookies will created for domain "".

Scenario: I'll demonstrate the example where i forcefully insert WWW for home page. So on each login cookies create only for . I'll also demonstrate URL redirect when there is request for webpage don't have WWW in URL (i.e: and request for cookies.

Insert below code in your index.jsp (i.e: home page) at the start of the page.
// index.jsp
    String referer = request.getParameter("url");

    if (referer == null && !request.getHeader("host").contains("www")) {
    } else if (referer!=null && !referer.equals("index.jsp") && (referer.indexOf("www")<0 referer.indexof="" www="">10)) {
        referer = referer.substring(referer.indexOf("//") + 2, referer.length());
        referer = "http://www." + referer;

We use the else if code when there is a request come for other page except home page (i.e: So...

Now we must check each page's URL for WWW in it. Insert below code in every page or create one checkURL.jsp page and include it in every page.
        boolean login = true;
        /* Read cookies for
         * if you can read it then okay but you can't then set login = false;
         * It'll be redirected to index.jsp and insert WWW in its URL and redirect to that page again.
        StringBuffer requestURL = request.getRequestURL();
        if (request.getQueryString() != null) {
        String completeURL = requestURL.toString();

So now on cookies created only for . Browser no more sends cookie in request for .

Java - How to insert www in naked domain?

Lets consider you want to insert www in url forcefully for certain reasons. Its easy task you can handle by simple script that I'm gonna give you. Keep in mind you need to change the below code for your domain as per your need.

Scenario: I'm considering the home page will be redirected to . If you want your page will be redirect to then you must add this code to every page. Simple idea is make checkURL.jsp and paste the code in this page and include checkURL.jsp in every page.
    StringBuffer requestURL = request.getRequestURL();
    if (request.getQueryString() != null) {
    String completeURL = requestURL.toString();

    if (completeURL.indexOf("www")<0 || completeURL.indexOf("www")>10) {
        String referer = completeURL.substring(referer.indexOf("//") + 2, referer.length());
        referer = "http://www." + referer;
Now when user comes to the page it'll check the URL and if there is not www in URL it'll append and redirect it to desired page.

How to configure Subdomain in Tomcat 7?

Before we jump to solution let me write search queries used by users to do same so they will also get the solution.

  • Configure subdomain in apache tomcat 7.
  • Configuring Virtual Hosts.
  • Configure subdomain in server.xml
  • Configure subdomain in DNS.
  • Configure subdomain for java.
  • Configure subdomain step by step.
  • Configure subdomain on 

There is no perfect solution available to configure subdomain. I walk through 200-300 webpages and article to get the solution. I prefer the solution must be understandable. I'll show you how you can configure subdomain(s).

In this example we'll configure subdomain . You can also have your subdomain like . [Note : subdomain name must be lower case you can't give subdomain name as So keep in mind it won't work.]

Step 1: You need to modify the server.xml file available in ${catalina.home}/conf/server.xml or tomcat_installation/conf/server.xml. All you need is append below line of code with in <Engine> Tag.
<Host appbase="webapps/ROOT/m" autodeploy="true" name="" unpackwars="true" xmlnamespaceaware="false" xmlvalidation="false">
<Context docbase="/usr/local/software/tomcat7/webapps/ROOT/m" path="" reloadable="true"></Context>
<Context antijarlocking="false" antiresourcelocking="false" docbase="/usr/local/software/tomcat7/webapps/manager" path="/manager" privileged="true" reloadable="true"></Context>
Things you need to change:

  • appbase : If you have folder where webapps folder is created then appbase will be just m . If folder is with in webapps then appbase will be webapps/m and so on...
  • name : change it with your domain name.
  • docbase in first context : Set the location of your folder with absolute path.
  • Second context : You can remove if you want or set it the the manager folder for your application.

Step 2: Edit DNS record for your website. Search for DNS editor on your website's admin panel. Follow below steps.

  • Go to List zones.
  • Edit your zones.
  • Add record.
  • Provide name
  • Set Type to A
  • Set Content to your Server IP Address.
  • Set TTL as per your want or 86400.

Note 1: DNS changes may take sometime if you are working on shared server or ask to your hosting provider.
Note 2: If you are working on windows then search on for edit hosts file for subdomain .

Step 3: Restart your Apache Tomcat 7.

Getting started with MySQL and Java

                MySQL is an opensource Relational Database Management System. Now a days it is used by most of  website and software. Apart from that if you are Entrepreneur it helps to cut the cost. I personally use MySQL on my website. 

                Some of you have any miss guided news about MySQL here is your answer. Facebook uses MySQL. Read more about it on MySQL website :

Facebook and MySQL statistics : 
  • Facebook process 60 million request in one second.
  • Facebook maintains database of more than 800 million users ; 500 million of them visits facebook daily
  • 350 million mobile user
  • 7 million application integrated with facebook platform.
  • Hope that's enough for you to understand what MySQL can handle...

Lets move to codding part quickly. Before you jump to any code download required software. Follow the links below to quick start : 

Database : ( MySQL )
  • MySQL Server
  • All of our support connectors
  • Workbench and sample models ( Provide database access using GUI )
  • MySQL Notifier
  • MySQL for Excel
  • MySQL for Visual Studio
  • Sample databases
  • Documentation

Library :

  • .jar file to connect database

Hope you have installed MySQL in your system. Now let me show you how you can connect to MySQL database with below code snippet.
import java.sql.*; // import SQL connection class
public final class MySQLDemo {
    public static final String dbhost = "jdbc:mysql://localhost:3306/javaQuery"; //javaQuery is schema name
    public static final String dbusername = "root";
    public static final String dbpassword = "root";
    public static final String dbdriver = "com.mysql.jdbc.Driver";

    public static void main(String[] args) {
        try {
            Class.forName(dbdriver); // Load driver
            Connection con = DriverManager.getConnection(dbhost, dbusername, dbpassword); // Create connection to database
            PreparedStatement selectData_stmt = con.prepareStatement("select * from DemoJavaQuery"); // Prepare query
            ResultSet selectData_rs = selectData_stmt.executeQuery(); // execute query and get data
            while({ //executes till last row available
                System.out.println(selectData_rs.getString("column_name")); // print data
             * Close connection if you don't need further.
             * If you don't close it will create problem when you deal with large application
        } catch (Exception e) {

For best practice read more on database:

Getting started with JSON and Java Web application

What is JSON?
JSON stands for JavaScript Object Notation. Its text-based open standard designed for human-readable data interchange. To know more about JSON read the wikipedia . Here is how JSON object holds the data.

    "firstName": "Vicky",
    "lastName": "Thakor",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    "phoneNumber": [
            "type": "home",
            "number": "212 555-1234"
            "type": "fax",
            "number": "646 555-4567"

Why use JSON in java web-application?
Its time to develop web-application that perform operation faster. Say if you want to process data without refreshing current page/content JSON is perfect solution for you. I'm going to show you quick demo with validating the email.

Download the JSON library for Java from sourceforge

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Validate Email Address</title>
        <input name="email" id="email"/>
        <span id="result"></span>
        <input type="button" value="check" id="check"/>
        <script src="../staticCDN/js/jquery-1.8.2.min.js"></script>
                var emailID = $("#email").val();
                    var obj = eval ("(" + data + ")");
                    var status = obj.status;
                        $("#result").html("Email is Okay!");
<%@page import="org.json.JSONObject"%>
<%@page import="javaQuery.validation.validate"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
String email = request.getParameter("email");
validate vEmail = new validate();
JSONObject status = new JSONObject();
    status.put("status", "SUCCESS");
    status.put("notify_error", "Email is Okay!");
    status.put("status", "FAIL");
    status.put("notify_error", "Provide valid email!");

Hope you get proper idea of JSON by checking all above codes. If you have any problem let me know.
Output of Demo:


How to put image in jFrame or Swing application?

            I've got so many requests on my website that how to put image in swing application or Jframe. Its very easy for one to understand. I hope you are using some IDE for creating swing application. I'm using Netbeans here to create one.

To place image on swing application you can use jLabel for that. If you are not using any IDE here is code for you.

private javax.swing.JLabel jLabel1;
jLabel1 = new javax.swing.JLabel();
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon_128.png")));
//Here image placed in package/folder called images. For better explanation read the whole article.

Now lets roll to IDE Netbeans. Netbeans implement same as above i wrote.

Step 1 : Create package/folder in project that contains images for your project.
  • Why is required so? : Say if you are building application for your client that requires images in that. Pointing image out of project folder will not be available in client's computer. So by placing/binding images within project will always available in *.jar file.

Step 2 : Create or place jLable in jFrame. 

Step 3 : Open up jLabel properties and browse icon.

properties jLabel

Step 4 : Select desired image either way from package (Recommended) or external image.

swing, netbeans

Step 5 : Press "Ok" and  now remove text of jLabel.


Output : Finally we've done it. You can move your image at your desired place.

Developers : How to attach video in your website using java?

After long time I'm back to javaQuery article. Today m gonna show you how google+, Facebook, Twitter embed videos in there post, Tweet, etc... I was working on this code. This code will cover all video website like Youtube, vimeo, etc... that contains video information in proper formation. Check out the below code to demonstrate the URL. This library is present in latest javaQuery API. Some website may not be support by this API.

* javaQueryAPI 7.0 or less
import javaQuery.j2ee.EmbedVideo;
public class Video {
    public static void main(String[] args) {
        String WebVideo = "";
        EmbedVideo em = new EmbedVideo();
        boolean flag = em.EmbedVideo("");
        //flag will return true if website/link contains video details in proper format.
        if (flag) {

            WebVideo = "Author:"+EmbedVideo.author_name;
            //Modify the Data as per your requirement like place the video in iframe
* javaQueryAPI 8.0 or above
* This code requires additional JSON library. You must include JSON lib to work this API. Its available in javaQueryAPI 8.0/lib folder on
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.embedvideo;

public class Demo {
    public static void main(String[] args) {
        embedvideo em = javaQueryBundle.create_embedvideo();
* output
* Pitbull - Rain Over Me ft. Marc Anthony
* Not Available
* 480
* 270
* PitbullVEVO
* <iframe allowfullscreen="" frameborder="0" height="270" src="" width="480"></iframe>
* YouTube

Once you done with the code. You can change the properties of video attachment for your page. Change the video CSS, width, height.

Check out the for download.

How to boost your website in Java?

Innovators making internet faster then our thoughts. Its also essential we have to serve our user best of it. User wants everything on finger tip like a blink of light. Some of you may searching for the content like

  • How to speed up site?
  • How to load site faster?
  • How to make Java, JSP, Servlet site fast?

To make your website secure and safe read this article How to create java website secure and safe?

I'll give you some tips to do it and you can see the effect its loading way much faster. Some content you ignored but it really matters when user have slow connection speed. Let me show how you made your site and its old idea to do it. Your site currently having this scenario as below.

This is how your site works if you didn't optimized it. Now we'll see how you can optimize if you didn't. Check your site grade using Yslow We'll do optimization and after that check your grade you'll see it increased.

Compress StyleSheet, javaScripts
You must compress content to make response faster. So it'll take less time to load. Removing whitespace, unwanted semi colons from the StyleeSheet, javaScript. Use the below online tool to compress it

  • StyleeSheet (CSS) - Tool compress css and give you compressed CSS. Compress CSS in .css file as well as data between <style></style>
  • Tool :
  • Note: This tool compress CSS but some time it made changes according standard CSS rules. If you made any tricks in CSS it'll be omitted. After compression test your CSS and make changes again  for tricky CSS
Note : Place StyleSheet at the TOP and javaScript before the </body>.

Compress images, Don't scale it.
Compress images using some software, or online so it load faster on client side. Below some sites that helps you to convert and compress images. Secondly don't scale images say image 128x128 and you try to show as a 30x30. Better to make that image 30x30 rather then showing 128x128 image using width = 30.

Combine static images
Combine all static png images. Say if you have menubar icons so combining all images in one will reduce http requests.

Remove Buffer
This is also required to flush the buffer. Put the below code between </head> <body> <% response.flushBuffer();%>

Few HTTP request
Combine all scripts in one file so it makes less parallel HTTP request. Say browser loads data after DNS look up(Domain Validation). So if you use multiple domain (image, script, etc... from other site) then it make DNS look up for every site. Try to minimize the HTTP request.Make HTTP request between 2-4 if possible. 

Set expire header for the content important task.
Browser it self store data in cache. But if you store data with out expiry. It'll load images, javascripts, stylesheets, etc... any time. Store data with proper expiry so it'll refresh data at that time only. All site have some static content like logo, menu image, script, stylesheet. Store this data at the client side so browse each time use data from cache. Browser doesn't make request for that data on server so server has to response less data. I'll show how you can do it.

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletResponse;

public class cacheControl implements javax.servlet.Filter {
    FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    public void doFilter(ServletRequest req,
            ServletResponse res,
            FilterChain chain)
            throws IOException, ServletException {
        String sCache = filterConfig.getInitParameter("cache");

        if (sCache != null) {
            ((HttpServletResponse) res).setHeader("Cache-Control", sCache);
        chain.doFilter(req, res);
    public void destroy() {
        this.filterConfig = null;

Create servlet using above code. Make an entry in web.xml if you are not using some IDE. Now set filer for what you want to set expiry header. Like *.css, *.js, *.png, etc....Copy paste the below code in web.xml . *.css, *.js, means every css from your domain, Below code have max-age=250000 mean it'll store data round about two days. You can also append *.png, *.jpg, etc... create proper filter.

            <param-value>public, max-age=250000</param-value>

Now check your grade using Yslow it would improve. The above filer response after some 2-3 request if you already opened site in your browser because browser already stored data. If your request comes from first time from that browser it'll store everything.

Compress content and serve to user.
Now we will pass data as a Gzip to client/user. All you need is find server.xml now find the Connector tag  and Append below code to it.

noCompressionUserAgents="gozilla, traviata"
It'll look like
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8084" protocol="HTTP/1.1" redirectPort="8443" compression="on" compressionMinSize="2048" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

How to create java website secure and safe?

Web site developer must keep in mind before publishing site that site has enough validation to keep site secure and safe. I'll give you some tips and tricks to keep your java website safe and secure. The tips helps to prevent hacker from hacking your java website.

How hacker try to hack your site?

  • Check server loop holes. (Server vulnerable)
  • Cross the validation of site by disabling scripts. (Site vulnerable)
  • Wrong inputs

Above are the simple way the hacker try to gain access in your site. The advance hacker can hack site by cracking server.

Note: Chinese Hacker can hack Google, This tips helps but not assure that its provide full protection. 

  • Choose best server

    • - If you are planning to host your java site. Please choose best server, ensure server's security. I prefer to use
    • - Planning to set up your own server. Use best anti virus, Strong firewall, Close all loop holes.

  • Cross - Validation

    • - Validation must required for the site.
    • - Client - Server both side validation to protect site.
    • - If you created javaScript to validate email, hacker disable the javaScript and give wrong input. When request come to server check email on server side also.

  • File Upload (If allowed to users)

    • - User not allowed to upload  ( .jsp, .java, .class, .jar ).
    • - Suppose if user allow to upload .jsp file then hacker can read other .jsp page using file reader. It'll print all your .jsp page code.

  • Check each and every input with proper validation at server side.

  • Handle all errors with proper output.(Display error pages)

    •    505 - Shows database query error on webpage and shows all code of page.
    •    404 - Content not found

If you have other idea you can comment it. This will help other to secure site built in java platform.