I'm taking an all-Java approach to Spring MVC configuration and cannot figure out how to associate a MultipartConfigElement
with my DispatcherServlet
programmatically.
Spring documentation states:
In order to use Servlet 3.0 based multipart parsing, you need to mark the DispatcherServlet with a "multipart-config" section in web.xml, or with a javax.servlet.MultipartConfigElement in programmatic Servlet registration...
http://docs.spring.io/spring/docs/4.0.4.RELEASE/spring-framework-reference/htmlsingle/#mvc-multipart
Here is my WebApplicationInitializer
code:
public class DispatcherServletInitializer implements WebApplicationInitializer {
private static final Logger logger = LoggerFactory.getLogger(DispatcherServletInitializer.class);
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebConfig.class);
//HOW CAN I ASSOCIATE THIS CONFIG WITH MY DISPATCHER SERVLET?
MultipartConfigElement config = new MultipartConfigElement("C:\\Temp", 20848820, 418018841, 1048576);
DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
How do I associate the MultipartConfigElement
with my DispatcherServlet
? I don't see any method like setMultipartConfiguration or any constructor that accepts it.
Also note that my WebConfig declares a MultipartResolver
:
@Bean
public StandardServletMultipartResolver multipartResolver(){
return new StandardServletMultipartResolver();
}
But the Spring documentation states:
Configuration settings such as maximum sizes or storage locations need to be applied at that Servlet registration level as Servlet 3.0 does not allow for those settings to be done from the MultipartResolver.
Any guidance would be greatly appreciated.
Looks like you need this:
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
dispatcher.setMultipartConfig(new MultipartConfigElement("/tmp", 1024*1024*5, 1024*1024*5*5, 1024*1024));