Vaadin 23+Spring Boot中UI与REST API路径配置问题求助
解决方案:Vaadin 23 + Spring Boot REST API 路径配置问题
1. 修正application.properties配置
确保Vaadin正确排除/api路径,不处理这类请求:
server.servlet.context-path=/project # Vaadin UI路径映射 vaadin.url-mapping=/ui/* # 排除API路径,交给Spring MVC处理 vaadin.exclude-urls=/api/** # 白名单Vaadin相关包,避免路由异常 vaadin.whitelisted-packages=com.yourpackage.ui,com.vaadin
2. 调整Spring Security配置
继承VaadinWebSecurity时,需明确放行/api路径,同时避免Vaadin缓存拦截API请求:
@Configuration @EnableWebSecurity public class SecurityConfig extends VaadinWebSecurity { @Override protected void configure(HttpSecurity http) throws Exception { // 优先放行所有/api路径,无需Vaadin认证 http.authorizeHttpRequests(auth -> auth.requestMatchers("/api/**").permitAll()); // 调用父类配置,处理Vaadin UI的认证和路由逻辑 super.configure(http); // 指定Vaadin登录页面的路径 setLoginView(http, LoginView.class, "/ui/login"); // 禁用Vaadin的请求缓存,防止API请求被重定向到UI页面 http.requestCache().requestCache(new NullRequestCache()); } @Override public void configure(WebSecurity web) throws Exception { // 让Spring Security忽略/api路径的拦截 web.ignoring().requestMatchers("/api/**"); super.configure(web); } }
3. 修正RestController路径映射
确保控制器使用/api前缀,让Spring MVC正确识别路由:
@RestController @RequestMapping("/api") public class TestRestController { @GetMapping("/hello") public ResponseEntity<String> hello() { return ResponseEntity.ok("Hello World!"); } }
4. 解决Postman返回Vaadin HTML的问题
该问题由内容协商逻辑或Vaadin错误路由导致,可通过以下方式修复:
- 请求时在Postman中添加请求头
Accept: text/plain或Accept: application/json,明确指定返回格式 - 在RestController方法上直接指定返回类型:
@GetMapping("/hello", produces = MediaType.TEXT_PLAIN_VALUE) - 全局配置Spring MVC内容协商规则,优先返回JSON/文本:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON) .mediaType("json", MediaType.APPLICATION_JSON) .mediaType("plain", MediaType.TEXT_PLAIN); } }
5. 排查要点
- 确认
vaadin.exclude-urls已正确配置/api/** - 检查Security配置中
/api/**是否同时被permitAll和web.ignoring()处理 - 验证RestController所在包是否被Spring扫描到(需在启动类包下或添加
@ComponentScan指定范围) - 测试时直接访问
http://localhost:8080/project/api/hello,查看控制台路由匹配日志
内容的提问来源于stack exchange,提问作者Szyu
相关产品推荐
相关产品推荐

