7

I am in process to capture Current URL as its being displayed in the browser's address bar in my JSP page and have few options to get it done.

In my current application, we are going to put web-server in front of our application server as than it seems that those values will be of not any use.

I have another way to take help of javascript's document.URL but i am not sure how reliable it is going to be.

I need to get the details about the location of the user and if I can use getRequestURI(), it will return me something like www.abc.com/abc/search.jsp.

In short, all I want to capture the URL being there in the address bar of the browser and save it in a hidden field of my JSP page.

I am not sure what is the best way to achieve this.

Community
  • 1
  • 1
Umesh Awasthi
  • 23,407
  • 37
  • 132
  • 204

3 Answers3

10

In Java, you can do this:

 public static String getCurrentUrl(HttpServletRequest request){

    URL url = new URL(request.getRequestURL().toString())

    String host  = url.getHost();
    String userInfo = url.getUserInfo();
    String scheme = url.getProtocol();
    String port = url.getPort();
    String path = request.getAttribute("javax.servlet.forward.request_uri");
    String query = request.getAttribute("javax.servlet.forward.query_string");
    URI uri = new URI(scheme,userInfo,host,port,path,query,null)
    return uri.toString();
}
Reed Grey
  • 508
  • 6
  • 10
4

If you want a javascript solution, you can use window.document.location object and its properties:

console.log(window.document.location.protocol);
http:
console.log(window.document.location.host);
stackoverflow.com
console.log(window.document.location.port);

console.log(window.document.location.href);
http://stackoverflow.com/questions/10845606/get-current-url-in-webapplication
console.log(window.document.location.pathname);
/questions/10845606/get-current-url-in-webapplication

You can understand other parameters reading this article at MDN.

Zlatko
  • 18,936
  • 14
  • 70
  • 123
  • Thanks for the input and i am settling down to javascript based solution.i have a question will `window.document.location.pathname` will pick the query string if any append to the URL? – Umesh Awasthi Jun 01 '12 at 07:18
  • Nope, that is the location.search bit. Check out the link I'm adding to my answer. – Zlatko Jun 02 '12 at 07:06
4

You can create a hidden field in your form

<input type="hidden" id="myurl" name="myurl"/>

then write a javascript

<script type="text/javascript">
document.getElementById('myurl').value = window.location.href
</script>

is that help?

James
  • 13,571
  • 6
  • 61
  • 83