use*_*118 15 spring web.xml welcome-file programmatic-config
目前我有一个Web应用程序,我们使用web.xml来配置应用程序.web.xml有welcome-file-list.
<web-app>
...
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
Run Code Online (Sandbox Code Playgroud)
我们计划使用spring框架并使用java类进行应用程序配置.
class MyApplication extends WebApplicationInitializer {
public void onStartUp(ServletContext context){
...
}
}
Run Code Online (Sandbox Code Playgroud)
如何在此java类中指定welcome-file-list?
Omk*_*kar 19
在使用纯Java Based Configuration开发Spring MVC应用程序时,我们可以通过使我们的应用程序配置类扩展WebMvcConfigurerAdapter类并覆盖addViewControllers方法来设置主页,我们可以在其中设置默认主页,如下所述.
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.myapp.controllers" })
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
Run Code Online (Sandbox Code Playgroud)
它返回home.jsp可以作为主页的视图.无需创建自定义控制器逻辑即可返回主页视图.
用于addViewControllers方法的JavaDoc 说 -
配置预配置了响应状态代码的简单自动控制器和/或视图以呈现响应主体.这在不需要自定义控制器逻辑的情况下很有用 - 例如,渲染主页,执行简单的站点URL重定向,返回带有HTML内容的404状态,带有无内容的204等等.
第二种方法 - 对于静态HTML文件主页,我们可以在配置类中使用下面的代码.它将index.html作为主页返回-
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
Run Code Online (Sandbox Code Playgroud)
第三种方式 - 下面的请求映射"/"也将返回home视图,该视图可以作为应用程序的主页.但建议采用上述方法.
@Controller
public class UserController {
@RequestMapping(value = { "/" })
public String homePage() {
return "home";
}
}
Run Code Online (Sandbox Code Playgroud)
public interface WebApplicationInitializer
Interface要在Servlet 3.0+环境中实现,以便以编程方式配置ServletContext - 而不是(或可能与传统的基于web.xml的方法相结合).
但是你仍然需要web.xml中的最小配置,比如for
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Run Code Online (Sandbox Code Playgroud)
小智 5
@EnableWebMvc
@Configuration
@ComponentScan("com.springapp.mvc")
public class MvcConfig extends WebMvcConfigurerAdapter {
...
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/*.html").addResourceLocations("/WEB-INF/pages/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
...
}
Run Code Online (Sandbox Code Playgroud)
这可能会有所帮助。
| 归档时间: |
|
| 查看次数: |
18726 次 |
| 最近记录: |