Get Rid of http://x.action URL

Change Struts URL extension suffix .do .action

If you notice, many web applications deployed over the web have .do or .action at the end of URL’s. One can deliberately use these kinds of url’s.

But usually it is the default behavior of the framework/tool being used then a deliberate attempt by the developer.

Struts based web applications are the widest of them to have .do or .action suffixes with URL’s.

That is because of the numerous tutorials and books have adopted .do as a convention for Struts 1 based applications. The same applied to Struts 2. The good news is that one can easily change or get rid of extension suffixes in Struts 1 and Struts2. A question then arises as to how come the suffixed come into the URL’s.

Struts 1

If we look at a form being written using Struts 1 tag libraries, it doesn’t have any .do or .action. Here is a sample form in a JSP page of a Struts based application.


        
        
    

As we can see that we are using the form tag of the struts-html tag library. So let us dig more into that tag by having a look at the struts-taglib.jar. Inside this library, look for org.apache.struts.taglib.html.FormTag.java

In the FormTag.java we can see the code for the attribute action:
After analyzing the code for FormTag.java, the URL pattern being used for mapping ActionServlet, is being used as the URL suffix by the custom tags.
In the web.xml we generally have something like this:


        actionServlet
        *.do
    

TO make all the URL to have suffix of .who instead of .do, change the mapping to:


        actionServlet
        *.who
    

Struts 2

But if we look at the web.xml for struts 2 based application, we have


        struts2D
        org.apache.struts2.dispatcher.FilterDispatcher
    
    
        struts2D
        /*
    

So from where .action does come from?
In case of Struts 2, the extension suffix comes from the property struts.action.extension.

The value for this property can be changed to any suitable value by setting this property in the struts.xml
An example for changing the URL's in case of Struts 2 to .do is given below:


 
      
 
     
       
         login.jsp
       
     
 
   


With the above structure in the struts.xml, all the URL's will have .do as the extension suffix. Similarly, to get rid of the extension suffix at all, use the following xml code in struts.xml


 
      
 
     
       
          login.jsp
       
     
 
   

Hope this tutorial will help people in customizing their applications while using the Struts framework.

Web Application - Automatically Show Login Page After Session Timeout

Show Login Page After Session Timeout

One can define the session timeout time in the web.xml of a web application and can also set it programmatically by using the Session API.

The server automatically takes care of the session invalidation once the timeout has occurred with user don’t doing any activity.

But to make an application more user friendly, one should prompt user about the session being going to expire and proper message once the session has expired. Some applications will prefer to redirect the user to login page once the session has timed out.

All these features of session timeout detection are not supported by J2EE API’s. One needs to use JavaScript to show warning messages and redirect users.

There are many ways by using which the session timeout can be made more graceful. The two most used approaches are to use the timer functions in JavaScript or to use cookies.

With timer functions, an initial timer equal to the session timeout is set and the JavaScript function decrements the seconds and shows warning and directs user at appropriate time.

With cookies, two cookies with expiration time of warning time and session timeout time are created and a JavaScript function constantly polls for the existence of the cookies. If the cookies are not found, the corresponding actions are performed.
The sample code for both the approaches is shown below. The code is for showing warning messages only. You can create similar functions for handling the session timeout scenario. Also, please note that the code shown below is not of production quality is intended to give you the start only.



function alertUser(){
    var a_p = "";
    var d = new Date();
    var curr_hour = d.getHours();
    if (curr_hour < 12) {
        a_p = "AM";
    }
    else {
        a_p = "PM";
    }

    if (curr_hour == 0) {
        curr_hour = 12;
    }

    if (curr_hour > 12) {
        curr_hour = curr_hour - 12;
    }

    var curr_min = d.getMinutes();

    curr_min = curr_min + "";

    if (curr_min.length == 1) {
        curr_min = "0" + curr_min;
    }

    var curT=curr_hour+':'+curr_min+' '+a_p;
    document.getElementById('sessionExpirySpace').style.display='block';
    alert(You have been inactive and have not saved your work for last 10    Minutes.\n Please save your work in next 5 minutes to avoid  any Data Loss due to  Session timeout.');
}




Similarly for cookies based approach, the code should look something like:


function createCookie(name,value) {
    argv=arguments;
    argc=arguments.length;
    var today = new Date(); 
    today.setTime( today.getTime() );
    var expires=argv[2];
    expires = expires * 1000 * 60;
    var expires_date = new Date( today.getTime() + (expires) ); 
    path=(argc>3) ? argv[3] : null;
    domain=(argc>4) ? argv[4] : null;
    secure=(argc>5) ? argv[5] : false;
    document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ';path=/;';
    checkCookie('MyAPP','Test');
}
function checkCookie(name,value) {
    var today = new Date(); 
    var curr_hour = today.getHours();
    var curr_min = today.getMinutes();
    if (curr_min < 9) 
        curr_min = '0' + curr_min;

    var n=name;
    var i = document.cookie.indexOf(name);
    if(i==-1)
       alert('Dear User,Your session has been inactive and you have not saved your  work for the last 25 Minutes.\nPlease save your work within next 5 minutes.\n \t\t\t\t' +  ' (Message at'+ ' ' + curr_hour + ':' + curr_min + ' Hrs)');
    else
        setTimeout("checkCookie('MyAPP','Test')",10000);
}



There are other things to keep in mind like:
1) What if user opens a new tab and opens the website
2) What if the user manually logouts

About Daemon Threads in Java

About Daemon Threads in Java



There can be two types of threads in Java viz User Thread and Daemon Thread. All the threads created by a user are user threads. A thread becomes Daemon thread when the user says so. User threads are meant for the program code.

On the other hand Daemon threads are service provider threads. They should not be used to run your program code but some system code. The run() method for a daemon thread is typically an infinite loop that waits for a service request. These threads run in parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon threads are terminated instantly. Thus one should never rely on daemon code to perform any program code.

For better understanding consider a well known example of Daemon thread : Java garbage collector. The Garbage collector runs as a low priority daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly. 

Daemon threads are typically used to perform services for your application/applet. The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution. Use daemons as the minions they are. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.
To specify that a thread is a daemon thread, call the setDaemon() method with the argument true. To determine if a thread is a daemon thread, use the accessor method isDaemon().

15 Must Know Java Interview Questions After 2 Years of Experience

Interview Questions that every developer should have the answer

Enterprise Java Application development is growing every day and new features being introduced but the the beginners have always start from the basics. The questions listed below are what in general a Java developer should be able to answer after 2 years of experience. (Assuming no prior exposure to Java)




UPDATE: The answers can be found at http://bateru.com/news/2011/03/484/

Core Java
1) What is the purpose of serialization?
2) What is the difference between JDK and JRE?
3) What is the difference between equals and ==?
4) When will you use Comparator and Comparable interfaces?
5) What is the wait/notify mechanism?
6) What is the difference between checked and unchecked exceptions?
7) What is the difference between final, finally and finalize?
JEE
8) What is the difference between web server and app server?
9) Explain the Struts1/Struts2/MVC application architecture?
10) What is the difference between forward and sendredirect?
General
11) How does a 3 tier application differ from a 2 tier one?
12) How does the version control process works?
13) What is the difference between JAR and WAR files?
Databases
14) What is a Left outer join?
15) What is the difference between UNION and UNION ALL?

How to Send HTTP POST Request in Java

How do I send a POST request using Java?


A POST request can be used for multiple purposes on the web. It can be used for performing the Create or Update operations for various resources. The most common usage of a POST request is in the form of a FORM on an HTML page. 


 


The HTTP protocol doesn’t say anything about the best way to use the POST request but with the web the HTML has become the standard for issuing POST request.
One can also send POST requests from javascript (AJAX), .Net, PHP or Java based programs. Recently I had written a program to issue a POST request in Java. 


If you have server listening for requests then this program code can be handy. In my case, it was a REST web service which was listening for POST requests. One can also issue these HTTP requests for servlets too.
The code follows:


package test;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {
 public static void main(String[] args) throws IOException {
  URL url = new URL("http://localhost:8080/resttest/services/Order/3");
  HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
  httpCon.setDoOutput(true);
  httpCon.setRequestMethod("POST");
  OutputStreamWriter out = new OutputStreamWriter(
      httpCon.getOutputStream());
  System.out.println(httpCon.getResponseCode());
  System.out.println(httpCon.getResponseMessage());
  out.close();
 }
}


Please replace the URL with the actual URL where the server application is listening for POST requests.

One can also use the same code for issuing the other HTTP requests which are GET,PUT and DELETE. To achieve that, change the line:


httpCon.setRequestMethod("POST");
to
httpCon.setRequestMethod("GET");
httpCon.setRequestMethod("PUT");
httpCon.setRequestMethod("DELETE");