TheLegend27
TheLegend27

Reputation: 121

Vaadin: How to get URL Parameter?

I'm using Vaading 14 and i have a View with @Route("B/details/:id?"). How do I get the :id value? So i have a view A that navigates with UI.getCurrent().navigate("B/details",parameters); to view B. The Url then looks like B/details/2.

Upvotes: 0

Views: 1376

Answers (1)

Avec
Avec

Reputation: 1761

Difference between URL Parameter and Query Parameters

URL Parameter: domain.com/path/value
Query Parameter: domain.com/path?key=value&key2=value2

For URL Parameter try something like this

Example url: http://localhost:8080/B/details/123

@Route("B/details/:id?") // ? meaning optional
public class DetailsView extends Div implements BeforeEnterObserver {

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
       final Optional<String> optionalId = event.getRouteParameters().get("id");
       optionalId.ifPresentOrElse(id -> {
         // id found     
       }, 
       () -> {
         // id not found     
       });
    }
}

URL Parameter documentation found here

For Query Parameters try something like this

Example url: http://localhost:8080/B/details?id=123&other=value1

@Route("B/details")
public class DetailsView extends Div implements HasUrlParameter<String> {

   @Override
   public void setParameter(BeforeEvent event, @OptionalParameter String parameter) {
        Location location = event.getLocation();
        QueryParameters queryParameters = location.getQueryParameters();

        Map<String, List<String>> parametersMap = queryParameters
                .getParameters();

        System.out.println(parametersMap);
    }
}

Example Output: {other=[value1], id=[123]}

Query Parameters documentation found here.

Hint: You can implement HasUrlParameter in both cases if you want and even both at the same time. The optional parameter represents the URL parameter.

Tips

If you want to identify a resource use URL parameter. If you need things like paging, filtering, sorting, etc use query parameters. In this case it might seem like you want to identify one or zero resources. In that case use URL parameter. When there is no parameter I usually display a list of all depending on the context.

Upvotes: 4

Related Questions