2017-08-26 32 views
2

假設我有Spring Rest API,名爲application,它的請求映射到/api。這意味着我打電話例如GET方法來獲取用戶的列表:Spring Rest API和不帶後綴的靜態Web內容訪問

localhost:8080/application/api/users 

運作良好。我的目標是讓簡單的靜態html文件與此API一起引用對方。我需要找到index.html文件並將其作爲主頁。

localhost:8080/application/ 

它正確地顯示我index.html使用:

@RequestMapping(value = "/", method = RequestMethod.GET) 
public String homePage(ModelMap model) { 
    return "home"; 
} 

@Configuration 
@ComponentScan(basePackages = "net.nichar.application") 
@EnableWebMvc 
public class ApplicationConfiguration extends WebMvcConfigurerAdapter { 

@Bean 
public ViewResolver viewResolver() { 
    InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 
    resolver.setPrefix("/WEB-INF/pages/"); 
    resolver.setSuffix(".html"); 
    resolver.setExposeContextBeansAsAttributes(true); 
    return resolver; 
} 

在哪裏我鬥爭了另一個文件與<a href=...>導航在同一文件夾index2.htmlindex3.html而不需要明確寫出後綴html。我試圖實現訪問像

localhost:8080/application/index2 

的網頁,而無需使用其他@RequestMapping(除了第一個映射的主頁)。

還有一個問題,有沒有辦法在路徑導航中「跳過」文件夾?爲了清楚起見,我希望把這些HTML文件webapp/static文件夾,但是我有訪問他們喜歡

localhost:8080/application/static/... 

我試圖遵循的教程不久有關Spring資源映射,但是他們沒有人描述的解決任何類似的問題。我不使用Spring Boot。

謝謝你的幫助。


不久:

如何訪問文件 - >使用:

webapp/WEB-INF/pages/index.html --> localhost:8080/application 
webapp/static/index2.html  --> localhost:8080/application/index2 
webapp/static/index3.html  --> localhost:8080/application/index3 
+0

可能重複[Spring Boot not serving static content](https://stackoverflow.com/questions/24661289/spring-boot-not-serving-static-content) –

+0

@AbhijitSarkar不,我不使用Spring啓動:) –

+0

好吧,我回縮我的近距離投票,因爲我提到的答案是特定於Boot。 –

回答

2

您可以使用類似的東西,

@Configuration 
public class MvcConfig extends WebMvcConfigurerAdapter { 

@Override 
public void addViewControllers(ViewControllerRegistry registry) { 
    registry.addViewController("/login").setViewName("login"); 
    registry.addViewController("/welcome").setViewName("welcome"); 
    registry.addViewController("/about").setViewName("about"); 
    registry.addViewController("/contact").setViewName("contact"); 
} 

哪裏登錄映射登錄.html,並歡迎映射到welcome.html。它不需要@RequestMapping,但仍需要顯式映射。

+0

可能是最好的答案。儘管看起來我不會避免手動解析特定的URL來查看。 –