我正在使用 Spring MVC 开发一个基于纯 Java 且没有 web.xml 配置的 Web 应用程序。我编写了下面的类来加载 bean 并设置 url 模式。如何设置欢迎文件?
public class MyAppWebAppIntializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appCtx = new AnnotationConfigWebApplicationContext();
appCtx.register(ApplicationContextConfig.class);
Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appCtx));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
最佳答案
在使用纯Java配置开发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");
}
}
它返回可以用作主页的home.jsp
View 。无需创建自定义 Controller 逻辑即可返回主页 View 。
addViewControllers 的 JavaDoc方法说 -
Configure simple automated controllers pre-configured with the response status code and/or a view to render the response body. This is useful in cases where there is no need for custom controller logic -- e.g. render a home page, perform simple site URL redirects, return a 404 status with HTML content, a 204 with no content, and more.
第二种方式 - 对于静态 HTML 文件主页,我们可以在配置类中使用以下代码 -
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
第三种方式 - 下面的请求映射“/”也将返回 home.jsp,它可以用作应用程序的主页。但建议采用上述过程。
@Controller
public class UserController {
@RequestMapping(value = { "/" })
public String homePage() {
return "home";
}
}
关于spring - 使用纯Java配置且没有web.xml开发spring mvc应用程序时如何设置欢迎文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595675/