Using URI fragments

Reading Fragment when Initializing UI

URI fragments can either be used for initializing the UI and/or read or modified in any listener. In the UI.init method you get a “VaadinRequest request” parameter. The UI’s Page contains a information about the HTTP request used to initialize the application and you can get the URI fragment using

  1. getPage().getUriFragment()

A simple init that depends on the URI fragment is thus:

Java

  1. public class MyUI extends UI {
  2. @Override
  3. protected void init(VaadinRequest request) {
  4. layout = new VerticalLayout();
  5. layout.setMargin(true);
  6. setContent(layout);
  7. Label label = new Label("Hello, your fragment is "
  8. + getPage().getUriFragment());
  9. layout.addComponent(label);
  10. }
  11. }

Reading Fragment Changes

The URI fragment can be changed also when the application is running, either manually in the location bar in browser or from user code. These changes can be caught with a FragmentChangedListener. Notice, however, that there is no event fired for the initial URL fragment. The easiest way to handle both cases in the same way is to call the same method from the FragmentChangedListener and the init method:

Java

  1. public class MyUI extends UI {
  2. // ...
  3. // React to fragment changes
  4. getPage().addUriFragmentChangedListener(new UriFragmentChangedListener() {
  5. @Override
  6. public void uriFragmentChanged(UriFragmentChangedEvent source) {
  7. handleFragment(source.getUriFragment());
  8. }
  9. });
  10. // Handle the fragment received in the initial request
  11. handleFragment(getPage().getUriFragment());
  12. addComponent(new Button("Show and set fragment", new Button.ClickListener() {
  13. @Override
  14. public void buttonClick(ClickEvent event) {
  15. handleFragment(getPage().getUriFragment());
  16. getPage().setUriFragment("customFragment");
  17. }
  18. }));

Reading and Writing the Fragment

To later on read the fragment you can use

  1. Page.getCurrent().getUriFragment();

and to set the fragment

  1. Page.getCurrent().setUriFragment(String fragment);