📄 dispatcherservlet.java
字号:
* Initialize the MultipartResolver used by this class.
* If no bean is defined with the given name in the BeanFactory
* for this namespace, no multipart handling is provided.
*/
private void initMultipartResolver() throws BeansException {
try {
this.multipartResolver =
(MultipartResolver) getWebApplicationContext().getBean(MULTIPART_RESOLVER_BEAN_NAME);
if (logger.isInfoEnabled()) {
logger.info("Using MultipartResolver [" + this.multipartResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isInfoEnabled()) {
logger.info("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
"': no multipart request handling provided");
}
}
}
/**
* Initialize the LocaleResolver used by this class.
* If no bean is defined with the given name in the BeanFactory
* for this namespace, we default to AcceptHeaderLocaleResolver.
*/
private void initLocaleResolver() throws BeansException {
try {
this.localeResolver = (LocaleResolver) getWebApplicationContext().getBean(LOCALE_RESOLVER_BEAN_NAME);
if (logger.isInfoEnabled()) {
logger.info("Using LocaleResolver [" + this.localeResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
this.localeResolver = (LocaleResolver) getDefaultStrategy(LocaleResolver.class);
if (logger.isInfoEnabled()) {
logger.info("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME +
"': using default [" + this.localeResolver + "]");
}
}
}
/**
* Initialize the ThemeResolver used by this class.
* If no bean is defined with the given name in the BeanFactory
* for this namespace, we default to a FixedThemeResolver.
*/
private void initThemeResolver() throws BeansException {
try {
this.themeResolver = (ThemeResolver) getWebApplicationContext().getBean(THEME_RESOLVER_BEAN_NAME);
if (logger.isInfoEnabled()) {
logger.info("Using ThemeResolver [" + this.themeResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
this.themeResolver = (ThemeResolver) getDefaultStrategy(ThemeResolver.class);
if (logger.isInfoEnabled()) {
logger.info("Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME +
"': using default [" + this.themeResolver + "]");
}
}
}
/**
* Initialize the HandlerMappings used by this class.
* If no HandlerMapping beans are defined in the BeanFactory
* for this namespace, we default to BeanNameUrlHandlerMapping.
*/
private void initHandlerMappings() throws BeansException {
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
getWebApplicationContext(), HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList(matchingBeans.values());
// We keep HandlerMappings in sorted order.
Collections.sort(this.handlerMappings, new OrderComparator());
}
}
else {
try {
Object hm = getWebApplicationContext().getBean(HANDLER_MAPPING_BEAN_NAME);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(HandlerMapping.class);
if (logger.isInfoEnabled()) {
logger.info("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}
/**
* Initialize the HandlerAdapters used by this class.
* If no HandlerAdapter beans are defined in the BeanFactory
* for this namespace, we default to SimpleControllerHandlerAdapter.
*/
private void initHandlerAdapters() throws BeansException {
// Find all HandlerAdapters in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
getWebApplicationContext(), HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
Collections.sort(this.handlerAdapters, new OrderComparator());
}
else {
// Ensure we have at least some HandlerAdapters, by registering
// default HandlerAdapters if no other adapters are found.
this.handlerAdapters = getDefaultStrategies(HandlerAdapter.class);
if (logger.isInfoEnabled()) {
logger.info("No HandlerAdapters found in servlet '" + getServletName() + "': using default");
}
}
}
/**
* Initialize the HandlerExceptionResolver used by this class.
* If no bean is defined with the given name in the BeanFactory
* for this namespace, we default to no exception resolver.
*/
private void initHandlerExceptionResolvers() throws BeansException {
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
getWebApplicationContext(), HandlerExceptionResolver.class, true, false);
this.handlerExceptionResolvers = new ArrayList(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
Collections.sort(this.handlerExceptionResolvers, new OrderComparator());
}
else {
try {
Object her = getWebApplicationContext().getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, no HandlerExceptionResolver is fine too.
this.handlerExceptionResolvers = getDefaultStrategies(HandlerExceptionResolver.class);
}
}
}
/**
* Initialize the ViewResolvers used by this class.
* If no ViewResolver beans are defined in the BeanFactory
* for this namespace, we default to InternalResourceViewResolver.
*/
private void initViewResolvers() throws BeansException {
if (this.detectAllViewResolvers) {
// Find all ViewResolvers in the ApplicationContext,
// including ancestor contexts.
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
getWebApplicationContext(), ViewResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.viewResolvers = new ArrayList(matchingBeans.values());
// We keep ViewResolvers in sorted order.
Collections.sort(this.viewResolvers, new OrderComparator());
}
}
else {
try {
Object vr = getWebApplicationContext().getBean(VIEW_RESOLVER_BEAN_NAME);
this.viewResolvers = Collections.singletonList(vr);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default ViewResolver later.
}
}
// Ensure we have at least one ViewResolver, by registering
// a default ViewResolver if no other resolvers are found.
if (this.viewResolvers == null) {
this.viewResolvers = getDefaultStrategies(ViewResolver.class);
if (logger.isInfoEnabled()) {
logger.info("No ViewResolvers found in servlet '" + getServletName() + "': using default");
}
}
}
/**
* Return the default strategy object for the given strategy interface.
* <p>Default implementation delegates to <code>getDefaultStrategies</code>,
* expecting a single object in the list.
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
* @throws BeansException if initialization failed
* @see #getDefaultStrategies
*/
protected Object getDefaultStrategy(Class strategyInterface) throws BeansException {
List strategies = getDefaultStrategies(strategyInterface);
if (strategies.size() != 1) {
throw new BeanInitializationException(
"DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
}
return strategies.get(0);
}
/**
* Create a List of default strategy objects for the given strategy interface.
* <p>The default implementation uses the "DispatcherServlet.properties" file
* (in the same package as the DispatcherServlet class) to determine the class names.
* It instantiates the strategy objects and satisifies ApplicationContextAware
* if necessary.
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
* @throws BeansException if initialization failed
*/
protected List getDefaultStrategies(Class strategyInterface) throws BeansException {
String key = strategyInterface.getName();
try {
List strategies = null;
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
strategies = new ArrayList(classNames.length);
for (int i = 0; i < classNames.length; i++) {
Class clazz = Class.forName(classNames[i], true, getClass().getClassLoader());
Object strategy = BeanUtils.instantiateClass(clazz);
if (strategy instanceof ApplicationContextAware) {
((ApplicationContextAware) strategy).setApplicationContext(getWebApplicationContext());
}
strategies.add(strategy);
}
}
else {
strategies = Collections.EMPTY_LIST;
}
return strategies;
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class for interface [" + key + "]", ex);
}
}
/**
* Expose the DispatcherServlet-specific request attributes and
* delegate to <code>doDispatch</code> for the actual dispatching.
* @see #doDispatch
*/
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherServlet with name '" + getServletName() + "' received request for [" +
request.getRequestURI() + "]");
}
// Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.
Map attributesSnapshot = null;
if (request.getAttribute(UrlPathHelper.INCLUDE_URI_REQUEST_ATTRIBUTE) != null) {
logger.debug("Taking snapshot of request attributes before include");
attributesSnapshot = new HashMap();
Enumeration attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith(DispatcherServlet.class.getName())) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}
// Make framework objects available for handlers.
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
try {
doDispatch(request, response);
}
finally {
// Restore the original attribute snapshot, in case of an include.
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
/**
* Process the actual dispatching to the handler.
* <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the servlet's installed
* HandlerAdapters to find the first that supports the handler class.
* <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or
* handlers themselves to decide which methods are acceptable.
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
*/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
ModelAndView mv = null;
try {
processedRequest = checkMultipart(request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// Apply preHandle methods of registered interceptors.
if (mappedHandler.getInterceptors() != null) {
for (int i = 0; i < mappedHandler.getInterceptors().length; i++) {
HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// Apply postHandle methods of registered interceptors.
if (mappedHandler.getInterceptors() != null) {
for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -