Vaadin中Cookies.get(request,常量)方法获取逻辑及代码疑问
我来帮你拆解这段代码的逻辑,以及如何实现用Cookies.get()读取主题Cookie的操作——其实核心就是在自定义的ServletService里,拿到原生的Http请求对象,再读取Cookie即可。
首先,你贴的代码是截断的,完整的逻辑应该是重写VaadinCDIServletService的getConfiguredTheme方法,因为这个方法负责决定当前请求使用的主题。下面是补全后的完整代码,我会逐行解释:
import com.vaadin.flow.server.Constants; import com.vaadin.flow.server.VaadinCDIServlet; import com.vaadin.flow.server.VaadinCDIServletService; import com.vaadin.flow.server.VaadinRequest; import com.vaadin.flow.server.VaadinServletService; import com.vaadin.flow.server.ServiceException; import com.vaadin.flow.server.Cookies; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.Cookie; public class CustomVaadinCDIServlet extends VaadinCDIServlet { @Override protected VaadinServletService createServletService(DeploymentConfiguration deploymentConfiguration) throws ServiceException { final VaadinCDIServletService service = new VaadinCDIServletService(this, deploymentConfiguration) { @Override public String getConfiguredTheme(VaadinRequest vaadinRequest) { // 1. 从Vaadin请求中拿到底层的HttpServletRequest HttpServletRequest nativeRequest = (HttpServletRequest) vaadinRequest.getNativeRequest(); // 2. 使用Vaadin的Cookies工具类获取主题Cookie Cookie themeCookie = Cookies.get(nativeRequest, Constants.VAADIN_THEME_COOKIE_NAME); // 3. 如果Cookie存在且有值,就用它作为当前主题 if (themeCookie != null && !themeCookie.getValue().isBlank()) { return themeCookie.getValue(); } // 4. 如果没有Cookie,就回退到父类的默认逻辑(比如用配置文件里的默认主题) return super.getConfiguredTheme(vaadinRequest); } }; service.init(); return service; } }
关键步骤解释:
- 获取原生请求对象:Vaadin的
VaadinRequest是对底层Http请求的封装,通过getNativeRequest()可以拿到真正的HttpServletRequest,这是Cookies.get()方法需要的参数。 - 主题Cookie的含义:
Constants.VAADIN_THEME_COOKIE_NAME是Vaadin内置的常量,对应的值是"vaadin-theme"——这是Vaadin用来存储用户主题偏好的默认Cookie名称。如果你的前端通过代码设置过这个Cookie(比如用户切换主题时写入),后端就能读到。 - 回退逻辑:如果Cookie不存在(比如用户第一次访问),就调用父类的
getConfiguredTheme,它会读取你在application.properties、web.xml或者Vaadin配置里设置的默认主题。
额外注意点:
- 确保导入的是
com.vaadin.flow.server.Cookies和com.vaadin.flow.server.Constants,别导错包。 - 这个逻辑适用于Vaadin 14及以上的版本,因为这些版本的ServletService和主题机制是一致的。
- 如果你需要自定义Cookie名称,可以替换
Constants.VAADIN_THEME_COOKIE_NAME为你自己的字符串,但要确保前端写入的Cookie名称和后端读取的一致。
内容的提问来源于stack exchange,提问作者Bartosz Kolej
相关产品推荐
相关产品推荐

