2014-06-25 32 views
2

如果這感覺重複,我會收集很多人問這個問題,但我一直無法找到有效的答案。在同一路徑上共享靜態內容和mvc控制器

我有一個使用maven構建的web應用程序。我使用Spring 4 MVC提供了一個RESTful Json API。我也有很多靜態內容(html,css,js),我使用Angular.js在數據API上添加了一張漂亮的臉蛋。

對於我的生活,我無法弄清楚如何同時得到這兩個服務,而不會弄亂他們的路徑。

  • 我真的很想去{APP_ROOT}/people/{id}在我的瀏覽器,並直接與我的REST API交互,沒有任何廢話約/api//rest/

  • 我真的很想去{APP_ROOT}/css/style.css在我的瀏覽器,並送達從src/main/webapp/css/style.css內容沒有任何廢話約resourcesstatic

  • 此外,我真的很想CONFI古爾所有這一切都與註解的Java類,而不是有任何web.xmlapplication-context.xml

所以,春季調度的servlet應處理所有的REST資源的路徑,然後回落到默認的Tomcat /靜態內容的Jetty處理程序。我認爲這正是場景默認servlet處理程序是用於?我似乎無法得到它的工作。

這些都是我的相關配置類:

WebAppInitializer.java

public class WebAppInitializer extends 
     AbstractAnnotationConfigDispatcherServletInitializer { 


    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class<?>[0] ; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return new Class<?>[] { WebConfig.class}; 
    } 

    @Override 
    protected String[] getServletMappings() { 
     return new String[] { "/*" }; 
    } 

    @Override 
    protected Filter[] getServletFilters() { 

     CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); 
     characterEncodingFilter.setEncoding("UTF-8"); 
     return new Filter[] { characterEncodingFilter}; 
    } 

} 

WebConfig.java

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = {"my.example.package"}) 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
     configurer.enable(); 
    } 
} 

有了這個配置,我可以與REST API互動,但不是靜態內容。默認的servlet處理程序似乎不起作用。

回答

0

要訪問像CSS js或html這樣的靜態資源,請將所有這些文件保存在模塊的webapp文件夾中。假設你的靜態資源都放在src /主/ web應用/靜態路徑,你可以在上下文中的XML做MVC資源映射像下面現在

<mvc:resources mapping="/index-dev.html" location="/static/index-dev.html"/> 
<mvc:resources mapping="/index.html" location="/static/index.html"/> 
<mvc:resources mapping="/app.js" location="/static/app.js"/> 
<mvc:resources mapping="/appinit.js" location="/static/appinit.js"/> 
<mvc:resources mapping="/extjs/**" location="/static/extjs/"/> 
<mvc:resources mapping="/app/**" location="/static/app/"/> 
<mvc:resources mapping="/static/**" location="/static/static/"/> 
<mvc:resources mapping="/static/**" location="/static/"/> 

,因爲你想這樣做沒有XML你可以做你的WebConfig類像例如

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/index.html").addResourceLocations("/static/index.html"); 

}下面

+0

仙人您好,感謝的響應。 – Dave

+0

這仍然看起來並不理想,因爲我必須手動列出每個文件。或者我需要把某些「靜態」分支放在一邊,這是我試圖避免的主要事情之一。當沒有有效的彈簧控制器時,確實有辦法優雅地回退到提供靜態內容的tomcat/jetty?那不是默認的sevlet處理程序應該做什麼? – Dave

+0

此外,用這種方法,我將如何獲得'索引。html'可直接從瀏覽器中的「{APP_ROOT}」訪問? – Dave

相關問題