Getting the URL in the address bar.

I am currently using:

String url = Page.getCurrent().getLocation().toString(); to get the url in the address bar of the vaadin app. But the problem is that the app is redirected from
www.mywebsite.freehost.com
to
www.mywebsite.com
and the code that I am using is getting the wrong url. It is getting the old url. I need the url from the redirect. How can I do this? Does anyone know?

Try this:

(1)get the current Vaadin request:

import com.vaadin.server.VaadinService;
VaadinRequest vaadinRequest = VaadinService.getCurrentRequest();

(2)convert it to VaadinServletRequest, and then get the HttpServletRequest from it:

HttpServletRequest httpServletRequest = ((VaadinServletRequest)vaadinRequest).getHttpServletRequest();

(3)get the URL the client used to make the request.

String requestUrl = httpServletRequest.getRequestURL().toString();

I did not test if it work.
So please try it, and tell me if the result is correct

Alternatively, you could try getting it with
JavaScript
with window.location.href.

-Olli

I think the JavaScript solution has 2 problems:
(1)

The JavaScript is executed AFTER the server request that is currently processed returns… they are all executed sequentially AFTER THE REQUEST IS DONE

So you can not execute it, and get the result immediately in the server side code.

(2)and because of (1),

you can not return values from the JavaScript

So, in the server side code, you can not get the result of the JavaScript

See:
https://vaadin.com/docs/-/part/framework/advanced/advanced-javascript.html

You can’t return values from JavaScript, true, but you can add a function callback with JavaScript.getCurrent().addFunction(), which you can then use to get the value to your server-side code. Not the most elegant solution, but it works.

-Olli

I am redirecting my app from openshift to login.mywebsite.com. The code that you provided is giving me the url for openshift, and not for login.mywebsite.com. Do you have a work around for this?

Can you show us your code which cause this problem?

Any Idea how to achieve the same in Vaadin 14 (Spring Boot)?

[This Github issue]
(https://github.com/vaadin/flow/issues/1897) discusses some methods for accessing the current page URL (in Flow, so Vaadin 10+).

It sounds like the current “best” approach is to retrieve it using JavaScript from [Location]
(https://developer.mozilla.org/en-US/docs/Web/API/Location). Here is an example.

UI.getCurrent().getPage().executeJs("return window.location.href").then(String.class, location -> {
	Notification.show(String.format("Location: '%s'", location));
})

If you only want the path (no host or protocol), then use window.location.pathname. If you only want the query string, then use window.location.search.