![](/img/trans.png)
[英]Spring MVC with Java based config - 404 not found for static resources
[英]Spring MVC 4 Java Config with Static HTML Views
我正在嘗試構建一個由Spring MVC 4支持的無.jsp文件的單頁HTML / Angular應用程序。
當用戶到達根URL(例如http://myapp.com/ )時,我想發送單頁HTML文檔(index.html)。
但是,我是Spring MVC的Java配置的ServletMapping
, ServletMapping
, ViewResolver
和ResourceHandler
的正確組合。
我知道“默認”或“索引”頁面可能會有一些其他配置,但我可能會誤會。
那么如何使Java配置的Spring MVC 4應用程序發送html文件?
檔案結構
/src
'-/main
|-/web-inf
'-/webapp
|-index.html (want to send this)
'-/app
|-/partials
'-app.js
WebAppConfig.java
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/").addResourceLocations("/index.html");
}
IndexController.java
@RequestMapping("/")
public void index() {
System.out.println("pls"); // executes
// Have tried returning "index" and "index.html"
}
WebInitializer.java
@Override
protected String[] getServletMappings() {
// have tried with "/" as well
return new String[] { "/*" };
}
我認為您應該添加以下內容:
<mvc:view-controller path="/" view-name="index"/>
在您的dispathcer-servlet
文件中。
無論哪種方式,這里都有一些可行的解決方案-萬一每個人都需要針對其特定用例的解決方案。
如果您不想調用控制器方法而只提供文件。
WebInitializer.java:
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
Web.xml
<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
WebConfig.java
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("index.html").addResourceLocations("/index.html ");
}
如果您想在登陸時調用控制器方法。
web.xml中不需要歡迎文件列表
WebInitializer.java:
@Override
protected String[] getServletMappings() {
return new String[] { "/*" };
}
WebConfig.java
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("index.html").addResourceLocations("/index.html ");
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setSuffix(".html");
return viewResolver;
}
Controller.java
@RequestMapping("/")
public String index() {
return "index";
}
希望能幫助到別人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.