JiangYongKang
12/26/2018 - 7:20 AM

servlet3.0 去除 web.xml

package com.jiuxian;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * Author: LIU ZEJUN
 * Date: 2018-12-26 10:49:00
 * Comment:
 */


public class WebInitializer implements WebApplicationInitializer {


    /**
     * WebApplicationInitializer 是spring 提供配置Servlet 3.0 + 配置的接口,从而替代web.xml
     * @param servletContext
     */
    @Override
    public void onStartup(ServletContext servletContext) {
        //注册配置类
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MvcConfig.class);
        context.setServletContext(servletContext);

        //注册DispatcherServlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        dispatcher.addMapping("/");
        dispatcher.setLoadOnStartup(1);
    }
}