⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 multiactioncontroller.java

📁 spring的源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * Copyright 2002-2005 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.multiaction;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContextException;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.LastModified;
import org.springframework.web.servlet.support.SessionRequiredException;
import org.springframework.web.util.NestedServletException;

/**
 * Controller implementation that allows multiple request types to be
 * handled by the same class. Subclasses of this class can handle several
 * different types of request with methods of the form
 *
 * <pre>
 * ModelAndView actionName(HttpServletRequest request, HttpServletResponse response);</pre>
 *
 * May take a third parameter HttpSession in which an existing session will be required,
 * or a third parameter of an arbitrary class that gets treated as command
 * (i.e. an instance of the class gets created, and request parameters get bound to it)
 *
 * <p>These methods can throw any kind of exception, but should only let propagate
 * those that they consider fatal, or which their class or superclass is prepared to
 * catch by implementing an exception handler.
 *
 * <p>This model allows for rapid coding, but loses the advantage of compile-time
 * checking. It is similar to a Struts 1.1 DispatchAction, but more sophisticated.
 * Also supports delegation to another object.
 *
 * <p>An implementation of the MethodNameResolver interface defined in this package
 * should return a method name for a given request, based on any aspect of the request,
 * such as its URL or an "action" parameter. The actual strategy can be configured
 * via the "methodNameResolver" bean property, for each MultiActionController.
 *
 * <p>The default MethodNameResolver is InternalPathMethodNameResolver; further included
 * strategies are PropertiesMethodNameResolver and ParameterMethodNameResolver.
 *
 * <p>Subclasses can implement custom exception handler methods with names such as:
 *
 * <pre>
 * ModelAndView anyMeaningfulName(HttpServletRequest request, HttpServletResponse response, ExceptionClass exception);</pre>
 *
 * The third parameter can be any subclass or Exception or RuntimeException.
 *
 * <p>There can also be an optional lastModified method for handlers, of signature:
 *
 * <pre>
 * long anyMeaningfulNameLastModified(HttpServletRequest request)</pre>
 *
 * If such a method is present, it will be invoked. Default return from getLastModified
 * is -1, meaning that the content must always be regenerated.
 *
 * <p>Note that method overloading isn't allowed.
 * 
 * <p>See also description of workflow performed by superclasses
 * <a href="AbstractController.html#workflow">here</a>.
 *
 * <p><b>Note:</b> For maximum data binding flexibility, consider direct usage
 * of a ServletRequestDataBinder in your controller method, instead of relying
 * on a declared command argument. This allows for full control over the entire
 * binder setup and usage, including the invocation of Validators and the
 * subsequent evaluation of binding/validation errors.
 * 
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Colin Sampaleanu
 * @see MethodNameResolver
 * @see InternalPathMethodNameResolver
 * @see PropertiesMethodNameResolver
 * @see ParameterMethodNameResolver
 * @see org.springframework.web.servlet.mvc.LastModified#getLastModified
 * @see org.springframework.web.bind.ServletRequestDataBinder
 */
public class MultiActionController extends AbstractController implements LastModified  {
		
	/** Suffix for last-modified methods */
	public static final String LAST_MODIFIED_METHOD_SUFFIX = "LastModified";

	/** Default command name used for binding command objects: "command" */
	public static final String DEFAULT_COMMAND_NAME = "command";

	/** Log category to use when no mapped handler is found for a request */
	public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";

	/** Additional logger to use when no mapped handler is found for a request */
	protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);


	/**
	 * Helper object that knows how to return method names from incoming requests.
	 * Can be overridden via the methodNameResolver bean property
	 */
	private MethodNameResolver methodNameResolver = new InternalPathMethodNameResolver();

	/** List of Validators to apply to commands */
	private Validator[] validators;

	/** Object we'll invoke methods on. Defaults to this. */
	private Object delegate;

	/** Methods, keyed by name */
	private Map handlerMethodMap;
	
	/** LastModified methods, keyed by handler method name (without LAST_MODIFIED_SUFFIX) */
	private Map lastModifiedMethodMap;
	
	/** Methods, keyed by exception class */
	private Map exceptionHandlerMap;


	/**
	 * Constructor for MultiActionController that looks for handler methods
	 * in the present subclass.Caches methods for quick invocation later.
	 * This class's use of reflection will impose little overhead at runtime.
	 * @throws ApplicationContextException if the class doesn't contain any
	 * action handler methods (and so could never handle any requests).
	 */
	public MultiActionController() throws ApplicationContextException {
		setDelegate(this);
	}
	
	/**
	 * Constructor for MultiActionController that looks for handler methods in delegate,
	 * rather than a subclass of this class. Caches methods.
	 * @param delegate handler class. This doesn't need to implement any particular
	 * interface, as everything is done using reflection.
	 * @throws ApplicationContextException if the class doesn't contain any handler methods
	 */
	public MultiActionController(Object delegate) throws ApplicationContextException {
		setDelegate(delegate);
	}
	
	
	/**
	 * Set the method name resolver that this class should use.
	 * Allows parameterization of handler method mappings.
	 */
	public final void setMethodNameResolver(MethodNameResolver methodNameResolver) {
		this.methodNameResolver = methodNameResolver;
	}
	
	/**
	 * Return the MethodNameResolver used by this class.
	 */
	public final MethodNameResolver getMethodNameResolver() {
		return this.methodNameResolver;
	}
	
	/**
	 * Set the Validators for this controller.
	 * The Validator must support the specified command class.
	 */
	public final void setValidators(Validator[] validators) {
		this.validators = validators;
	}

	/**
	 * Return the Validators for this controller.
	 */
	public final Validator[] getValidators() {
		return validators;
	}


	/**
	 * Set the delegate used by this class. The default is <code>this</code>,
	 * assuming that handler methods have been added by a subclass.
	 * This method is rarely invoked once the class is configured.
	 * @param delegate class containing methods, which may be the present
	 * class, the handler methods being in a subclass
	 * @throws ApplicationContextException if there aren't any valid request
	 * handling methods in the subclass.
	 */
	public final void setDelegate(Object delegate) throws ApplicationContextException {
		if (delegate == null) {
			throw new IllegalArgumentException("delegate cannot be <code>null</code> in MultiActionController");
		}
		this.delegate = delegate;
		this.handlerMethodMap = new HashMap();
		this.lastModifiedMethodMap = new HashMap();
		
		// Look at all methods in the subclass, trying to find
		// methods that are validators according to our criteria
		Method[] methods = delegate.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			// We're looking for methods with given parameters.
			if (methods[i].getReturnType().equals(ModelAndView.class)) {
				// We have a potential handler method, with the correct return type.
				Class[] params = methods[i].getParameterTypes();
				
				// Check that the number and types of methods is correct.
				// We don't care about the declared exceptions.
				if (params.length >= 2 && params[0].equals(HttpServletRequest.class) &&
						params[1].equals(HttpServletResponse.class)) {
					// We're in business.
					if (logger.isDebugEnabled()) {
						logger.debug("Found action method [" + methods[i] + "]");
					}
					this.handlerMethodMap.put(methods[i].getName(), methods[i]);
					
					// Look for corresponding LastModified method.
					try {
						Method lastModifiedMethod = delegate.getClass().getMethod(
								methods[i].getName() + LAST_MODIFIED_METHOD_SUFFIX,
								new Class[] { HttpServletRequest.class } );
						// put in cache, keyed by handler method name
						this.lastModifiedMethodMap.put(methods[i].getName(), lastModifiedMethod);
						if (logger.isDebugEnabled()) {
							logger.debug("Found last modified method for action method [" + methods[i] + "]");
						}
					}
					catch (NoSuchMethodException ex) {
						// No last modified method. That's ok.
					}
				}
			}
		}
		
		// There must be SOME handler methods.
		// WHAT IF SETTING DELEGATE LATER!?
		if (this.handlerMethodMap.isEmpty()) {
			throw new ApplicationContextException("No handler methods in class [" + getClass().getName() + "]");
		}
		
		// Now look for exception handlers.
		this.exceptionHandlerMap = new HashMap();
		for (int i = 0; i < methods.length; i++) {
			if (methods[i].getReturnType().equals(ModelAndView.class) &&
					methods[i].getParameterTypes().length == 3) {
				Class[] params = methods[i].getParameterTypes();
				if (params[0].equals(HttpServletRequest.class) && 
					params[1].equals(HttpServletResponse.class) &&
					Throwable.class.isAssignableFrom(params[2])
				) {
					// Have an exception handler
					this.exceptionHandlerMap.put(params[2], methods[i]);
					if (logger.isDebugEnabled()) {
						logger.debug("Found exception handler method [" + methods[i] + "]");
					}
				}
			}
		}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -