「Spring」DispatcherServletがコントローラを割り当てる方法

構文
DispatcherServlet 変数名= new DispatcherServlet(xxx);
変数名.addServlet(xxx,xxx)
サンプルコード

public class TestWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {

        //  web application配置を読む
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);

        // DispatcherServlet作成と登録
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("user", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/user/*");
    }
}

web.xmlの定義

<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>user</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>user</servlet-name>
        <url-pattern>/user/*</url-pattern>
    </servlet-mapping>

</web-app>

 

SpringMVC

Posted by arkgame