You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vaadin 23中如何获取浏览器访问URL并存为Java字符串

Vaadin 23 中获取浏览器当前访问URL并存为String变量的实现

你可以直接通过Vaadin 23内置的请求上下文API拿到完整访问地址,不需要额外引入依赖,以下是可直接运行的实现方式:

具体实现

  • 核心依赖是Vaadin提供的VaadinService获取当前绑定的请求对象,注意代码执行时机必须是请求已经进入Vaadin上下文之后,不要在静态代码块、类初始化块、未绑定UI的异步线程里直接调用,会报空指针。
  • 针对你/createpassword路由对应的视图类,直接在视图构造方法(或onBeforeEnter路由生命周期钩子)里获取即可,能完整拿到带userId=1查询参数的全路径:
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.VaadinService;
import com.vaadin.flow.server.VaadinServletRequest;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import jakarta.servlet.http.HttpServletRequest;

@Route("createpassword")
public class CreatePasswordView extends VerticalLayout {

    public CreatePasswordView() {
        // 获取当前HTTP请求
        VaadinServletRequest vaadinRequest = (VaadinServletRequest) VaadinService.getCurrentRequest();
        HttpServletRequest rawRequest = vaadinRequest.getHttpServletRequest();
        
        // 拼接完整URL,包含域名、端口、路径、所有查询参数
        String fullAccessUrl = rawRequest.getRequestURL() + "?" + rawRequest.getQueryString();
        // 此时fullAccessUrl的值就是 http://localhost:8080/createpassword?userId=1
    }
}
  • 如果不需要查询参数,直接取rawRequest.getRequestURL().toString()就能拿到http://localhost:8080/createpassword部分。
  • 如果需要在异步线程里获取URL,必须先持有当前UI实例,加锁获取上下文后再调用:
// 先在主线程拿到UI实例
UI currentUi = UI.getCurrent();
new Thread(() -> {
    currentUi.access(() -> {
        VaadinServletRequest vaadinRequest = (VaadinServletRequest) VaadinService.getCurrentRequest();
        HttpServletRequest rawRequest = vaadinRequest.getHttpServletRequest();
        String fullAccessUrl = rawRequest.getRequestURL() + "?" + rawRequest.getQueryString();
        // 你的后续业务逻辑
    });
}).start();

注意:定时任务、应用启动钩子这类没有用户请求上下文的场景,无法通过上述方法获取URL,这类场景需要提前把URL作为参数传入对应逻辑。

内容的提问来源于stack exchange,提问作者Datta Dhonde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 22:33:22