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

Tomcat 9部署Spring Boot对接Angular应用出现404和CORS错误问题咨询

问题排查与解决方案

一、404错误排查解决

核心原因

Spring Boot 配置文件中的 server.port、server.servlet.context-path 是内置Tomcat的专属配置,部署到外置Tomcat时会完全失效,外置Tomcat以war包解压后的文件夹名作为context path。

排查步骤

  • 确认Tomcat端口:打开Tomcat安装目录下conf/server.xml,检查<Connector port="xxx"/>的端口值,确认未被WAMP或其他程序占用,启动日志无端口占用报错。
  • 确认部署结果:war包上传后检查Tomcat的webapps目录下是否生成springboot-proxy文件夹,查看logs/catalina.out日志确认Spring Boot应用启动无异常。
  • 验证测试接口:直接在浏览器访问 http://[Tomcat实际端口]/springboot-proxy/ws,正常应返回Hello World。如果仍404可删除application.properties中的server.servlet.context-path配置,外置Tomcat不需要该参数。

二、CORS跨域错误排查解决

核心问题

  1. CORS配置冲突且存在违规配置:你同时配置了Spring Security的CORS规则和WebMvc全局CORS规则,Spring Security优先级更高,WebMvc配置完全无效;且CORS规则中同时设置allowCredentials=true和allowedOrigins=*违反浏览器CORS规范,会直接导致跨域头不生效。
  2. CORS配置未注册为Bean:你写的corsConfigurationSource方法未加@Bean注解,Spring Security无法识别该配置,等于CORS规则未生效。
  3. 预检请求未放开权限:OPTIONS类型的预检请求不会携带认证信息,未在Spring Security中放开权限会被直接拦截,返回的响应无跨域头。

解决步骤

  • 删除无用的WebConfig全局跨域配置类,避免配置冲突。
  • 给corsConfigurationSource方法添加@Bean注解,修改CORS配置解决规则冲突:
@Bean // 必须加这个注解注册成Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration corsConfiguration = new CorsConfiguration();
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 允许凭证时不能用*,直接填前端实际地址http://localhost
    corsConfiguration.setAllowedOrigins(Collections.singletonList("http://localhost"));
    corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
    corsConfiguration.setMaxAge(3600L); // 缓存预检结果,避免每次请求都发预检
    source.registerCorsConfiguration("/**", corsConfiguration);
    return source;
}
  • 修改Spring Security的configure方法,放开OPTIONS请求权限:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            // 先放开所有OPTIONS预检请求
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(HttpMethod.GET, "/ws").permitAll()
            .antMatchers(HttpMethod.POST, "/ws/**").permitAll()
            // 剩余请求需要认证,记得补全这行,不然规则不完整
            .anyRequest().authenticated();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:00:02