2017-09-01 56 views
1

我在構建彈簧網站,它在子路由下對單頁面應用程序做出反應,我現在的URL結構應該像每個url路由和子路由的彈簧單頁「/ a/** => /a/index.html except/a/static/**」

localhost/admin/** => react app 
localhost/**  => spring thymeleaf/rest/websocket app for everything else 

react app mapping: 
localhost/admin/static/** => static react files 
localhost/admin/**   => react index.html for everything else 

Example of project resources structure: 
resources/ 
    admin/   <= my admin react files is here 
     index.html 
     static/ <= react css, js, statics 
    templates/  <= thymeleaf templates 
    static/  <= theamleaf static 
    ... 

,所以我需要轉發反應index.html文件每個URL路徑和子路徑。一切基本上單頁的應用程序,除了靜態文件

看起來像一個共同的任務,這裏是一些事情我已經嘗試:項目春天


全部工作演示+反應+我如何gradle這個建造項目,爲什麼能」牛逼放反應在不同的目錄中的文件(/資源/靜態爲例): https://github.com/varren/spring-react-example


無法使用forward:/admin/index.html/admin/**,因爲這將創建遞歸因爲admin/index.htmladmin/**下,並具有攔截admin/static/**莫名其妙。


不能在 WebMvcConfigurerAdapter

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/admin/**") 
      .addResourceLocations("classpath:/admin/"); 
} 

index.html只映射到/admin/index.html URL中使用addResourceHandlers,而這個選項差不多的作品,但只有當你從localhost/admin/index.html


thisthis訪問應用程序的反應和 this和許多其他鏈接,我也有點解決方案,但也許有通用的選項,我只是看不到

回答

0

現在,我使用自定義ResourceResolver解決這個

演示:https://github.com/varren/spring-react-example

@Configuration 
public class BaseWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 

     ResourceResolver resolver = new AdminResourceResolver(); 
     registry.addResourceHandler("/admin/**") 
       .resourceChain(false) 
       .addResolver(resolver); 


     registry.addResourceHandler("/admin/") 
       .resourceChain(false) 
       .addResolver(resolver); 
    } 


    private class AdminResourceResolver implements ResourceResolver { 
     private Resource index = new ClassPathResource("/admin/index.html"); 

     @Override 
     public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) { 
      return resolve(requestPath, locations); 
     } 

     @Override 
     public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) { 
      Resource resolvedResource = resolve(resourcePath, locations); 
      if (resolvedResource == null) { 
       return null; 
      } 
      try { 
       return resolvedResource.getURL().toString(); 
      } catch (IOException e) { 
       return resolvedResource.getFilename(); 
      } 
     } 

     private Resource resolve(String requestPath, List<? extends Resource> locations) { 

      if(requestPath == null) return null; 

      if (!requestPath.startsWith("static")) { 
       return index; 
      }else{ 
       return new ClassPathResource("/admin/" + requestPath); 
      } 
     } 
    } 
}