如何使用Spring Servlet使welcome-file-list工作?

时间:2015-07-03 11:16:27

标签: java spring servlets web.xml

这是我的代码:

public class Bootstrap implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {

        container.getServletRegistration("default").addMapping("/resources/*");

        AnnotationConfigWebApplicationContext servletContext =
                new AnnotationConfigWebApplicationContext();
        servletContext.register(ServletContextConfiguration.class);

        ServletRegistration.Dynamic dispatcher =
                container.addServlet("springDispatcher", new DispatcherServlet(servletContext));

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

继续前进:

@Configuration
@EnableWebMvc
@ComponentScan(
        basePackages = "biz.tugay.booksspringone.controller",
        useDefaultFilters = false,
        includeFilters = @ComponentScan.Filter(Controller.class)
)
public class ServletContextConfiguration {

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

}

和web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <welcome-file-list>
        <welcome-file>/welcome</welcome-file>
    </welcome-file-list>

</web-app>

和我的控制员:

@Controller
public class HelloController {
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("welcome");
        return modelAndView;
    }
}

当我部署我的应用程序并导航到localhost时:8080 /我希望调用 HelloController.welcome ,但事实并非如此。

只有在我明确访问 http://localhost:8080/welcome

时才会调用此方法

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

欢迎文件列表将找到该文件&#34;而不是请求&#34;你在标签中指定的。

所以

<welcome-file-list>
       <welcome-file>/welcome</welcome-file>
</welcome-file-list>

将查找具有您在视图解析器中指定的条件的文件,因此它将找到以下文件

/WEB-INF/views/welcome.jsp

创建该文件,您将被重定向到welcome.jsp作为主页。