📄 prototypecontroller.java
字号:
/**
* Is the supplied method a valid exception handler method?
*
* @param method 方法
* @return boolean 是否是异常处理方法
*/
private boolean isExceptionHandlerMethod(Method method) {
return (isHandlerMethod(method)
&& (method.getParameterTypes().length == 3)
&& Throwable.class.isAssignableFrom(method.getParameterTypes()[2]));
}
/**
* Registers the supplied method as a request handler.
*
* @param method 方法
*/
private void registerHandlerMethod(Method method) {
if (logger.isDebugEnabled()) {
logger.debug("Found action method [" + method + "]");
}
this.handlerMethodMap.put(method.getName(), method);
}
/**
* Registers a LastModified handler method for the supplied handler method
* if one exists.
*
* @param delegateIn delegate
* @param method 方法
*/
private void registerLastModifiedMethodIfExists(Object delegateIn,
Method method) {
// Look for corresponding LastModified method.
try {
Method lastModifiedMethod = delegateIn.getClass()
.getMethod(method.getName()
+ LAST_MODIFIED_METHOD_SUFFIX,
new Class[] {HttpServletRequest.class});
// Put in cache, keyed by handler method name.
this.lastModifiedMethodMap.put(method.getName(),
lastModifiedMethod);
if (logger.isDebugEnabled()) {
logger.debug(
"Found last modified method for action method ["
+ method + "]");
}
} catch (NoSuchMethodException ex) {
//logger.error(ex, ex);
logger.debug(ex);
// No last modified method. That's ok.
}
}
/**
* Registers the supplied method as an exception handler.
*
* @param method 注册的异常处理方法
*/
private void registerExceptionHandlerMethod(Method method) {
this.exceptionHandlerMap.put(method.getParameterTypes()[2], method);
if (logger.isDebugEnabled()) {
logger.debug("Found exception handler method [" + method + "]");
}
}
//---------------------------------------------------------------------
// Implementation of LastModified
//---------------------------------------------------------------------
/**
* Try to find an XXXXLastModified method, where XXXX is the name of a handler.
* Return -1, indicating that content must be updated, if there's no such handler.
*
* @param requestIn request
* @return long last modified
* @see org.springframework.web.servlet.mvc.LastModified#getLastModified(HttpServletRequest)
*/
public long getLastModified(HttpServletRequest requestIn) {
try {
String handlerMethodName = this.methodNameResolver
.getHandlerMethodName(requestIn);
Method lastModifiedMethod = (Method) this.lastModifiedMethodMap
.get(handlerMethodName);
//logger.info(lastModifiedMethodMap);
//logger.info(lastModifiedMethod);
if (lastModifiedMethod != null) {
try {
// invoke the last-modified method
Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate,
new Object[] {requestIn});
return wrappedLong.longValue();
} catch (Exception ex) {
// We encountered an error invoking the last-modified method.
// We can't do anything useful except log this, as we can't throw an exception.
logger.error("Failed to invoke last-modified method",
ex);
}
} // if we had a lastModified method for this request
} catch (NoSuchRequestHandlingMethodException ex) {
logger.error(ex, ex);
// No handler method for this request. This shouldn't happen, as this
// method shouldn't be called unless a previous invocation of this class
// has generated content. Do nothing, that's OK: We'll return default.
}
return -1L;
}
//---------------------------------------------------------------------
// Implementation of AbstractController
//---------------------------------------------------------------------
/**
* Handle the case where no request handler method was found.
* <p>The default implementation logs a warning and sends an HTTP 404 error.
* Alternatively, a fallback view could be chosen, or the
* NoSuchRequestHandlingMethodException could be rethrown as-is.
* @param ex the NoSuchRequestHandlingMethodException to be handled
* @param requestIn current HTTP request
* @param responseIn current HTTP response
* @return a ModelAndView to render, or <code>null</code> if handled directly
* @throws Exception an Exception that should be thrown as result of the servlet request
*/
protected ModelAndView handleNoSuchRequestHandlingMethod(
NoSuchRequestHandlingMethodException ex,
HttpServletRequest requestIn, HttpServletResponse responseIn)
throws Exception {
pageNotFoundLogger.warn(ex.getMessage());
responseIn.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
/**
* Create a new command object of the given class.
* <p>This implementation uses <code>BeanUtils.instantiateClass</code>,
* so commands need to have public no-arg constructors.
* Subclasses can override this implementation if desired.
*
* @param clazz command的类型
* @return Object command
* @throws Exception if the command object could not be instantiated
* @see org.springframework.beans.BeanUtils#instantiateClass(Class)
*/
protected Object newCommandObject(Class clazz) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Must create new command of class ["
+ clazz.getName() + "]");
}
return BeanUtils.instantiateClass(clazz);
}
/**
* Bind request parameters onto the given command bean.
* @param requestIn request from which parameters will be bound
* @param command command object, that must be a JavaBean
* @throws Exception in case of invalid state or arguments
*/
protected void bind(HttpServletRequest requestIn, Object command)
throws Exception {
logger.debug(
"Binding request parameters onto MultiActionController command");
ServletRequestDataBinder binder = createBinder(requestIn, command);
binder.bind(requestIn);
if (this.validators != null) {
for (int i = 0; i < this.validators.length; i++) {
if (this.validators[i].supports(command.getClass())) {
ValidationUtils.invokeValidator(this.validators[i],
command, binder.getBindingResult());
}
}
}
binder.closeNoCatch();
}
/**
* Create a new binder instance for the given command and request.
* <p>Called by <code>bind</code>. Can be overridden to plug in custom
* ServletRequestDataBinder subclasses.
* <p>Default implementation creates a standard ServletRequestDataBinder,
* and invokes <code>initBinder</code>. Note that <code>initBinder</code>
* will not be invoked if you override this method!
* @param requestIn current HTTP request
* @param command the command to bind onto
* @return the new binder instance
* @throws Exception in case of invalid state or arguments
* @see #bind
* @see #initBinder
*/
protected ServletRequestDataBinder createBinder(
HttpServletRequest requestIn, Object command) throws Exception {
ServletRequestDataBinder binder = new ServletRequestDataBinder(command,
getCommandName(command));
initBinder(requestIn, binder);
return binder;
}
/**
* Return the command name to use for the given command object.
* Default is "command".
* @param command the command object
* @return the command name to use
* @see #DEFAULT_COMMAND_NAME
*/
protected String getCommandName(Object command) {
return DEFAULT_COMMAND_NAME;
}
/**
* Initialize the given binder instance, for example with custom editors.
* Called by <code>createBinder</code>.
* <p>This method allows you to register custom editors for certain fields of your
* command class. For instance, you will be able to transform Date objects into a
* String pattern and back, in order to allow your JavaBeans to have Date properties
* and still be able to set and display them in an HTML interface.
* <p>Default implementation is empty.
* <p>Note: the command object is not directly passed to this method, but it's available
* via {@link org.springframework.validation.DataBinder#getTarget()}
* @param requestIn current HTTP request
* @param binder new binder instance
* @throws Exception in case of invalid state or arguments
* @see #createBinder
* @see org.springframework.validation.DataBinder#registerCustomEditor
* @see org.springframework.beans.propertyeditors.CustomDateEditor
*/
protected void initBinder(HttpServletRequest requestIn,
ServletRequestDataBinder binder) throws Exception {
initBinder((ServletRequest) requestIn, binder);
}
/**
* Initialize the given binder instance, for example with custom editors.
* @deprecated since Spring 2.0:
* use <code>initBinder(HttpServletRequest, ServletRequestDataBinder)</code> instead
*
* @param requestIn request
* @param binder ServletRequestDataBinder
* @throws Exception 异常
*/
protected void initBinder(ServletRequest requestIn,
ServletRequestDataBinder binder) throws Exception {
}
/**
* Determine the exception handler method for the given exception.
* Can return null if not found.
* @return a handler for the given exception type, or <code>null</code>
* @param exception the exception to handle
*/
protected Method getExceptionHandler(Throwable exception) {
Class exceptionClass = exception.getClass();
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception class ["
+ exceptionClass.getName() + "]");
}
Method handler = (Method) this.exceptionHandlerMap.get(exceptionClass);
//logger.info(exceptionHandlerMap);
//logger.info(handler);
while ((handler == null)
&& !exceptionClass.equals(Throwable.class)) {
if (logger.isDebugEnabled()) {
logger.debug(
"Trying to find handler for exception superclass ["
+ exceptionClass.getName() + "]");
}
exceptionClass = exceptionClass.getSuperclass();
handler = (Method) this.exceptionHandlerMap.get(exceptionClass);
}
return handler;
}
/**
* We've encountered an exception which may be recoverable
* (InvocationTargetException or HttpSessionRequiredException).
* Allow the subclass a chance to handle it.
* @param requestIn current HTTP request
* @param responseIn current HTTP response
* @param ex the exception that got thrown
* @return a ModelAndView to render the response
* @throws Exception 异常
*/
private ModelAndView handleException(HttpServletRequest requestIn,
HttpServletResponse responseIn, Throwable ex) throws Exception {
Method handler = getExceptionHandler(ex);
if (handler != null) {
return invokeExceptionHandler(handler, requestIn, responseIn,
ex);
}
// If we get here, there was no custom handler
if (ex instanceof Exception) {
throw (Exception) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
// Should never happen!
throw new NestedServletException("Unknown Throwable type encountered",
ex);
}
/**
* Invoke the selected exception handler.
*
* @param handler handler method to invoke
* @param requestIn request
* @param responseIn response
* @param ex Throwable
* @return ModelAndView mv
* @throws Exception 异常
*/
private ModelAndView invokeExceptionHandler(Method handler,
HttpServletRequest requestIn, HttpServletResponse responseIn,
Throwable ex) throws Exception {
if (handler == null) {
throw new NestedServletException("No handler for exception", ex);
}
// If we get here, we have a handler.
if (logger.isDebugEnabled()) {
logger.debug("Invoking exception handler [" + handler
+ "] for exception [" + ex + "]");
}
try {
Object returnValue = handler.invoke(this.delegate,
new Object[] {requestIn, responseIn, ex});
return massageReturnValueIfNecessary(returnValue);
} catch (InvocationTargetException ex2) {
Throwable targetEx = ex2.getTargetException();
if (targetEx instanceof Exception) {
throw (Exception) targetEx;
}
if (targetEx instanceof Error) {
throw (Error) targetEx;
}
// Should never happen!
throw new NestedServletException("Unknown Throwable type encountered",
targetEx);
}
}
/**
* Processes the return value of a handler method to ensure that it either returns
* <code>null</code> or an instance of {@link ModelAndView}. When returning a {@link Map},
* the {@link Map} instance is wrapped in a new {@link ModelAndView} instance.
*
* @param returnValue 返回值
* @return ModelAndView 根据returnValue生成的ModelAndView
*/
private ModelAndView massageReturnValueIfNecessary(Object returnValue) {
if (returnValue instanceof ModelAndView) {
return (ModelAndView) returnValue;
} else if (returnValue instanceof Map) {
return new ModelAndView().addAllObjects((Map) returnValue);
} else {
// Either returned null or was 'void' return.
// We'll assume that the handle method already wrote the response.
return null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -