Note 33 Advanced Techniques of Spring MVC - Alternatives to Spring MVC Configuration

1. Customize DispatcherServlet configuration 

AbstractAnnotationConfigDispatcherServletInitializer does more than it looks. In SpittrWebAppInitializer, the three methods originally written are only abstract methods that must be overloaded. But there are actually many more methods that can be overloaded to implement additional configuration. One of the methods of this class is customizeRegistration(). After the AbstractAnnotationConfigDispatcherServletInitializer registers the DispatcherServlet in the servlet container, it will call customizeRegistration() and pass the Registration.Dynamic obtained after the servlet is registered. By overriding the customizeRegistration() method, we can perform additional configuration on the DispatcherServlet. 

Requirement: Handling multipart requests and file uploads in Spring MVC

The registration of the DispatcherServlet is required to enable multipart requests. The customizeRegistration() method can be overloaded to set the MultipartConfigElement as follows:

 

1     @Override
2     protected void customizeRegistration(Dynamic registration) {
3         // TODO Auto-generated method stub
4         super.customizeRegistration(registration);
5         registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/uploads"));
6     }

 

Set the support for multipart, and set the temporary storage directory of uploaded files in "/tmp/spittr/uploads". 

Second, add other Servlet and Filter

According to the definition of AbstractAnnotationConfigDispatcherServletInitializer, it will create DispatcherServlet and ContextLoaderListener. However, if you want to register other servlets, filters or listeners, you need to create a new initializer. One of the nice things about Java-based initializers is that you can define any number of initializer classes. The easiest way is to implement Spring's WebApplicationInitializer interface. 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325724833&siteId=291194637