Servlet 3では、web.xmlを作成せずにアプリケーション側でサーブレットの設定を行うことができます。Spring Framework 3.2では、アプリケーションでSpring MVCのサーブレットクラスを利用する方法を提供します。
例
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> ..... <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <!-- Asynchronousサポート --> <async-supported>true</async-supported> <!-- MultipartResolverサポート --> <multipart-config> <location>/tmp</location> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config> </servlet> ..... <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/dispatcher/*</url-pattern> </servlet-mapping> ..... </web-app> |
上記web.xmlと同じ定義内容を初期化するためのソースを下記に示します。
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration.Dynamic; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class WebApp implements WebApplicationInitializer { @Override public void onStartup(final ServletContext servletContext)throws ServletException { final AnnotationConfigWebApplicationContext webAppContext = new AnnotationConfigWebApplicationContext(); webAppContext.setServletContext(servletContext); webAppContext.refresh(); final Dynamic servlet = servletContext.addServlet( "dispatcherServlet", new DispatcherServlet(webAppContext)); servlet.setLoadOnStartup(1); servlet.setAsyncSupported(true); //Asynchronousサポート MultipartConfigElement multipartConfig = new MultipartConfigElement(“/tmp”, 20848820, 418018841, 1048576); servlet.setMultipartConfig(multipartConfig); //MultipartResolverサポート servlet.addMapping("/dispatcher/*"); } } |
上記初期化クラスをコンテナから検索するために、javax.servlet.ServletContainerInitializerの設定を行ってください。
WebアプリケーションのMETA-INF\services\に、下記ファイルを追加します。
ファイル名:javax.servlet.ServletContainerInitializer
ファイル内容:org.springframework.web.SpringServletContainerInitializer
上記例で使用しているAsynchronousサポート機能とMultipartResolverサポート機能の詳しい使用方法はSpring 3.2オリジナルのマニュアルを参照してください。