How to define <welcome-file-list> and <error-page> in servlet 3.0's web.xml-less?

吃可爱长大的小学妹 提交于 2019-11-26 20:46:10

In Servlets 3.0 you don't need a web.xml for many cases, however, sometimes it's required or just useful. Your case is just one of them - there is no special annotations to define welcome-file list or error-pages.

Another thing is - would you really like to have them hardcoded? There are some valid use-cases for annotation / programmatic based configuration and for declarative configuration in XML. Moving to Servlets 3.0 doesn't necessarily means getting rid of web.xml at all cost.

I would find the entries you posted a better example of configuration in XML. Firstly - they can be changed from deployment to deployment and secondly - they affect whole application and not any particular Servlet.

For analog welcome-page-list put this in

@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");
    }
...
}

In Spring Boot or general Spring MVC app for following scenario:

Static files can be served from locations registered with a custom ResourceHandlerRegistry. We have a static resource index.html and it can accessed at localhost:8080/index.html. We want to just redirect localhost:8080/ request to localhost:8080/index.html, following code will can be used.

package in.geekmj.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
        "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/", "/index.html");
}
}

Now accessing localhost:8080/ will redirect to localhost:8080/index.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!