一、
1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherServletInitializer 的customizeRegistration() 来实现
// After AbstractAnnotation ConfigDispatcherServletInitializer registers DispatcherServlet with the servlet
// container, it calls the customizeRegistration() method, passing in the Servlet-
// Registration.Dynamic that resulted from the servlet registration. By overriding
// customizeRegistration() , you can apply additional configuration to DispatcherServlet .
// With the ServletRegistration.Dynamic that’s given to customizeRegistration() ,
// you can do several things, including set the load-on-startup priority by calling set-
// LoadOnStartup() , set an initialization parameter by calling setInitParameter() , and
// call setMultipartConfig() to configure Servlet 3.0 multipart support.
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("/tmp/spittr/uploads", 2097152, 4194304, 0));
}
2.通过重定WebApplicationInitializer的onStartup来注册servlet
package com.myapp.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import com.myapp.MyServlet;
public class MyServletInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
Dynamic myServlet =
servletContext.addServlet("myServlet", MyServlet.class);
myServlet.addMapping("/custom/**");
}
}
is a rather basic servlet-registering initializer class. It registers a servlet and maps it to a single path. You could use this approach to register DispatcherServlet manually. (But there’s no need, because AbstractAnnotationConfigDispatcher-
ServletInitializer does a fine job without as much code.)
3.通过重定WebApplicationInitializer的onStartup来注册filter
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
javax.servlet.FilterRegistration.Dynamic filter = servletContext.addFilter("myFilter", MyFilter.class);
filter.addMappingForUrlPatterns(null, false, "/custom/*");
}
4.To register one or more filters and map them to DispatcherServlet , all you need to do is override the getServletFilters() method of AbstractAnnotationConfigDispatcherServletInitializer .
@Override
protected Filter[] getServletFilters() {
return new Filter[] { new MyFilter() };
}
As you can see, this method returns an array of javax.servlet.Filter . Here it only returns a single filter, but it could return as many filters as you need. There’s no need to declare the mapping for the filters; any filter returned from getServletFilters() will automatically be mapped to DispatcherServlet