Spring welcome-file-list正确映射

时间:2011-09-14 10:48:40

标签: java spring spring-mvc

我知道在春天我必须定义welcome-file,它应该在WEB-INF文件夹之外,所以我这样定义:

的web.xml:

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>


<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

但实际上我的真实代码是在WEB-INF / jsp / contact.jsp

所以我总是要这样做:

<jsp:forward page="/index"></jsp:forward>

在我的控制器中,这意味着:

@RequestMapping("/index")
public String listContacts(Map<String, Object> map) {

    map.put("contact", new Contact());
    map.put("contactList", contactService.listContact());

    return "contact";
}

我怎样才能这样做,欢迎文件总是转到我的索引映射,这会导致contact.jsp?

如果这令人困惑,请随意提问...

4 个答案:

答案 0 :(得分:22)

@RequestMapping({"/index", "/"})

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

为我工作。

答案 1 :(得分:4)

请参阅我的回答:https://stackoverflow.com/a/15551678/173149或只是:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>/index.htm</url-pattern>    <<==  *1*
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.htm</welcome-file>   <<== *2*
</welcome-file-list>

答案 2 :(得分:2)

在java配置的情况下,您可以覆盖扩展WebMvcConfigurerAdapter的类中的两个方法

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("/index");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

如果您想明确地为index.html提供服务,请将其转换为资源覆盖同一类中的方法,如下所示:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/index.html").addResourceLocations("/WEB-INF/views/index.html");
}

当然addResourceLocations必须在选择的文件夹后面保存您的观点。

请参阅these samples

答案 3 :(得分:0)

尝试使用

<welcome-file-list>
  <welcome-file>/index</welcome-file>
</welcome-file-list>
相关问题