SpringAction学习三、Spring MVC:手动注册DispatcherServlet

通过扩展AbstractAnnotationConfigDispatcherServletInitializer,自动创建了DispatcherServlet和ContextLoaderListener。以下是示例代码:【首推这种方式】

package com.springmvc.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class HelloWorldIdInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[] { HelloWorldConfiguration.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

如果手动创建?

通过实现WebApplicationInitializer,创建一个新的Java初始化器。并重写了onStartup方法。

通过ServletContent的addServlet()方法,手动注册了一个setvlet。

AnnotationConfigWebApplicationContext是WebApplicationInitializer的实现类,用以加载Java配置类。

package com.springmvc.configuration;

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.ServletException;
import javax.servlet.ServletRegistration;

public class HelloWorldIdInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(HelloWorldConfiguration.class);
        context.setServletContext(servletContext);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");


    }
}

(代码中注册了一个DispatcherServlet,当然也可以注册其他的Servlet),如

//注册Serlvet
ServletRegistration.Dynamic myServlet = servletContext.addServlet("myServlet", MyServlet.class);
//映射到/custon/**
myServlet.addMapping("/custom/**");

通过该方法,也可以注册Filter

//注册Filter
FilterRegistration.Dynamic myFilter = servletContext.addFilter("myFilter", MyFilter.class);
///添加Filter的映射路径
myFilter.addMappingForUrlPatterns(null, false, "/custom/**");

 

你可能感兴趣的:(SpringAction,示例代码)