【问题标题】:Configure Spring Boot for SPA frontend为 SPA 前端配置 Spring Boot
【发布时间】:2017-04-07 17:48:48
【问题描述】:

我有一个应用程序,其中整个前端部分都在资源中。我想把事情分开。并且有单独的 UI 服务器,例如由 gulp 提供。

所以我假设我的服务器应该为客户端呈现的所有请求返回index.html

例如:我有 'user/:id' 路由,它通过角度路由进行管理,不需要任何服务器。如何配置服务器不会重新加载或将我重定向到任何地方?

我的安全配置如下(不知道它是否负责这些事情):

public class Application extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**", "/app/**", "/app.js")
                .permitAll().anyRequest().authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
                .logoutSuccessUrl("/").permitAll().and().csrf()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
    } 

【问题讨论】:

    标签: java angularjs spring gulp single-page-application


    【解决方案1】:

    对于路由,根据this guide at Using "Natural" Routes(特别是here),您必须添加一个执行以下操作的控制器:

    @Controller
    public class RouteController {
        @RequestMapping(value = "/{path:[^\\.]*}")
        public String redirect() {
            return "forward:/";
        }
    }
    

    然后使用Spring Boot,index.html加载到/,就可以加载资源了;路由由 Angular 处理。

    【讨论】:

    • 这并没有涵盖带有另一个正斜杠的 URL。例如。 localhost:8080/im-covered 和 localhost:8080/im/not/covered
    • @EpicPandaForce {[path:[^\\.]*} 到底是什么意思?它从何而来?我理解正则表达式,我不明白 Spring Boot 如何处理“路径”部分。
    • @BobbyBrown 不幸的是,我只知道我关注了this guide,并且成功了。
    • @EpicPandaForce 同样...我只是想弄清楚path 是什么。我猜@RequestMapping 采用类似 JSON 格式的对象。
    • 这是special syntax for named path variablespath: 表示该正则表达式匹配的部分 URL 将绑定到具有对应名称的 @PathVariable
    【解决方案2】:

    EpicPandaForce 有一个很好的答案,我想扩展它。以下端点也将允许匹配嵌套路由。如果您想拥有一个管理部分,您可以将其配置为返回不同的 index.html。

    @Controller
    class PageController {
    
        @GetMapping("/**/{path:[^\\.]*}")
        fun forward(request: HttpServletRequest): String? {
            if(request.requestURI.startsWith("/admin")) {
                return "forward:/admin/index.html"
            }
            return "forward:/index.html"
        }
    }
    

    此 RequestMapping(或 @GetMapping)通过排除任何包含句点(即“index.html”)的请求来工作。

    【讨论】:

      【解决方案3】:

      如果您将 Angular 与 Spring Data Rest 一起使用,我认为最直接的方法是使用角度哈希定位策略。

      只需将其放入应用模块的 providers 数组中即可:

      { provide: LocationStrategy, useClass: HashLocationStrategy }

      很明显,导入它。

      【讨论】:

      猜你喜欢
      • 2020-09-16
      • 2020-09-30
      • 2015-06-08
      • 2021-02-06
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      相关资源
      最近更新 更多