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 .
You are never sure that the technical solution you are providing is the best (at least in my case,needless to say ...it is not ).I prefer logical arguments as well as constructive criticisms from others on technical ground ,rather than just mute and dumb agreements.At times just few comments from others do help to think differently and come out with a far better implementation. I am here to accumulate some of my technical experiences and have some discussions with others on these topics .
Tuesday, June 29, 2010
Subscribe to:
Post Comments (Atom)
I can understand the problem, being a asp.net developer i will go for the URL REWRITTING feature with a http module.
ReplyDelete