2016-03-14 28 views
0

這是我第一次嘗試構建一個春天mvc應用程序。這就是我已經配置我的春天應用與靜態頁面的春天mvc部署掙扎

項目API初始化程序

public class ProjectApiInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 
    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class[] {ProjectApiConfiguration.class}; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return null; 
    } 

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

配置

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "com.rootpackage.api") 
public class ApiConfiguration { 
} 

注意Spring映射/。當我訪問的URL localhost:8080/client/<client_id>/token

控制器

@RestController 
public class ApiController { 
    @RequestMapping(value = "/client/{clientId}/token", consumes = APPLICATION_JSON_VALUE) 
    public ResponseEntity getClientToken(@PathVariable String clientId){ 
     Message msg = new Message("hello " + clientId); 
     return new ResponseEntity<>(msg, HttpStatus.OK); 
    } 
} 

我沒有任何web.xml這是工作的罰款。該API可通過localhost:8080/client/<client_id>/token訪問。

現在,我在webapp文件夾中創建了一個靜態html頁面,並試圖在localhost:8080/static_html.html頁面訪問它,但是tomcat返回了404。爲什麼?我在這裏失蹤了什麼?

+0

你配置了靜態資源處理程序嗎? –

+0

我有初始化和配置...沒有資源處理程序。它是什麼 ? –

回答

0

您應該配置一個資源處理程序,例如:

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "com.rootpackage.api") 
public class ApiConfiguration extends WebMvcConfigurerAdapter { 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/**").addResourceLocations("/public-resources/"); 
    } 
} 

其中「公共資源」是一個文件夾/包在你的JAR的類路徑。

+0

我在'addResourceHandlers'中加入了這一行...''registry.addResourceHandler(「/ **」) .addResourceLocations(「/ webapp /」);'我的靜態html頁面位於'webapp'目錄下。當我嘗試在'http:// localhost:8080/ .html'訪問它時,它返回了404 ...雖然我確實看到了被調用的「doFilters」方法。 –

+0

嘗試.addResourceLocations(「/」);而不是 –

+0

'webapp'目錄不是你的war文件的一部分。它代表一個Web應用程序根目錄。將你的文件直接放入該目錄或任何子目錄,並按照我們的建議(「/」或「/ dir-name /」)將相應路徑傳遞給'addResourceLocations'方法。 – pgiecek

0

如下更改您的ApiConfiguration類,將您的靜態文件放在Web應用程序根目錄下的static文件夾下並嘗試通過http://localhost:8080/static/some-html.html訪問它們。

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "com.rootpackage.api") 
public class ApiConfiguration extends WebMvcConfigurerAdapter { 

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

}