【问题标题】:Vaadin: How to get URL Parameter?Vaadin:如何获取 URL 参数?
【发布时间】:2025-12-07 22:45:01
【问题描述】:

我正在使用 Vaading 14,我有一个带有 @Route("B/details/:id?") 的视图。如何获得 :id 值? 所以我有一个视图 A,它使用 UI.getCurrent().navigate("B/details",parameters); 导航以查看 B。然后 URL 看起来像 B/details/2。

【问题讨论】:

标签: java vaadin


【解决方案1】:

URL参数和查询参数的区别

网址参数:domain.com/path/value
查询参数:domain.com/path?key=value&key2=value2

对于 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     
       });
    }
}

网址参数文档找到here

对于查询参数试试这样的

示例网址:http://localhost:8080/B/details?id=123&amp;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);
    }
}

示例输出:{other=[value1], id=[123]}

查询参数文档找到here

提示:如果您愿意,您可以在这两种情况下实现HasUrlParameter,甚至可以同时实现这两种情况。可选的parameter 代表URL 参数。

提示

如果要识别资源,请使用 URL 参数。如果您需要分页、过滤、排序等操作,请使用查询参数。在这种情况下,您似乎想要识别一个或零个资源。在这种情况下,请使用 URL 参数。当没有参数时,我通常会根据上下文显示所有参数的列表。

【讨论】:

  • 我在发布此消息之前自己对其进行了测试,它按预期工作。你实现BeforeEnterObserver了吗?我可以同时调用 url 的 http://localhost:8080/B/details/1http://localhost:8080/B/details 就好了。
  • 目标是用 B/details?id=1 而不是 details/1 调用它
  • 好的,那么您的问题中需要它。既然您提供了新信息,我将更改我的答案。