Tuesday, June 29, 2010

Generic solution to prepare the application URL from server end.

Problem description :
I was quite annoyed few days back when I got stuck for sometime while doing a very small task .
The requirement was to display an URL on a JSP page and the situation was such that, the URL value should be a DTO property value (may be populated by an Struts action class or whatever ) .
Say your application URL is "http://xyz.com:9080/PayrollApp".Now you want to display an URL which is like "http://xyz.com:9080/PayrollApp/edit.do".How to create such URL String ( without any sort of hard coding ) from an action class ? Well apparently it is quite simple , in fact it is , specially after you read this post , but trust me otherwise it is not.

The first thing that comes to our mind is "request.getContextPath()" will serve the purpose . Yes off course , but wait a minute ....it will do your job only partially . You will only get the application name (in this case the "PayrollApp" portion ) using request.getContextPath().


What about the previous parts ? The schema,host name ,port number ? How you will populate their value ? Confused ? Honestly speaking , I was .

Lets discuss about URLs in general . Generally what are the different parts of an URL ?
1.The first part is the protocol (here it is http).
2.The protocol is followed by ://
3.Next comes the host (in our example it is "xyz.com" )
4.You may have a port number also after the host name (9080 ) .
5. After the domain you may have your application name (as we have PayrollApp) .But always that is not the case.


Analysis and solution:

Well , the following code is self explanatory .Just use it ...

Sample Code:

String applicationPath = request.getScheme()+"://"+request.getServerName()+":"+
request.getServerPort()+request.getContextPath();


String finalURI=applicationPath+"/edit.do"

Notes :
Please note I have kept the "request.getServerPort()" , but that is not always the case .

1 comment:

  1. I can understand the problem, being a asp.net developer i will go for the URL REWRITTING feature with a http module.

    ReplyDelete