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

📄 multiactioncontroller.java

📁 一个关于Spring框架的示例应用程序,简单使用,可以参考.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
			throw new ApplicationContextException("No handler methods in class [" + getClass().getName() + "]");
		}
		
		// now look for exception handlers
		this.exceptionHandlerHash = 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.exceptionHandlerHash.put(params[2], methods[i]);
					if (logger.isInfoEnabled()) {
						logger.info("Found exception handler method [" + methods[i] + "]");
					}
				}
			}
		}
	}
	
	
	//---------------------------------------------------------------------
	// 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.
	 * @see org.springframework.web.servlet.mvc.LastModified#getLastModified(HttpServletRequest)
	 */
	public final long getLastModified(HttpServletRequest request) {
		try {
			String handlerMethodName = this.methodNameResolver.getHandlerMethodName(request);
			Method lastModifiedMethod = (Method) this.lastModifiedMethodHash.get(handlerMethodName);
			if (lastModifiedMethod != null) {
				try {
					// invoke the last-modified method
					Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, new Object[] { request });
					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 lastModified method", ex);
				}
			}	// if we had a lastModified method for this request
		}
		catch (NoSuchRequestHandlingMethodException 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.
		}
		// the default if we didn't find a method
		return -1L;
	}


	//---------------------------------------------------------------------
	// Implementation of Controller
	//---------------------------------------------------------------------

	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
	    throws Exception {
		try {
			String methodName = this.methodNameResolver.getHandlerMethodName(request);
			return invokeNamedMethod(methodName, request, response);
		}
		catch (NoSuchRequestHandlingMethodException ex) {
			pageNotFoundLogger.warn(ex.getMessage());
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return null;
		}
	}
	
	/**
	 * Invoke the named method.
	 * Use a custom exception handler if possible;
	 * otherwise, throw an unchecked exception;
	 * wrap a checked exception or Throwable
	 */
	protected final ModelAndView invokeNamedMethod(String method, HttpServletRequest request,
	                                               HttpServletResponse response) throws Exception {
		
		Method m = (Method) this.methodHash.get(method);
		if (m == null) {
			throw new NoSuchRequestHandlingMethodException(method, getClass());
		}

		try {
			// A real generic Collection! Parameters to method.
			List params = new ArrayList(4);
			params.add(request);
			params.add(response);
				
			if (m.getParameterTypes().length >= 3 && m.getParameterTypes()[2].equals(HttpSession.class) ){
				HttpSession session = request.getSession(false);
				if (session == null) {
					return handleException(
							request, response,
							new SessionRequiredException("Pre-existing session required for handler method '" + method + "'"));
				}
				params.add(session);
			}
			
			// If last parameter isn't of HttpSession type, it's a command.
			if (m.getParameterTypes().length >= 3 &&
					!m.getParameterTypes()[m.getParameterTypes().length - 1].equals(HttpSession.class)) {
				Object command = newCommandObject(m.getParameterTypes()[m.getParameterTypes().length - 1]);
				params.add(command);
				bind(request, command);
			}
			
			return (ModelAndView) m.invoke(this.delegate, params.toArray(new Object[params.size()]));
		}
		catch (InvocationTargetException ex) {
			// This is what we're looking for: the handler method threw an exception
			Throwable t = ex.getTargetException();
			return handleException(request, response, t);
		}
	}

	/**
	 * We've encountered an exception which may be recoverable
	 * (InvocationTargetException or SessionRequiredException).
	 * Allow the subclass a chance to handle it.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param t the exception that got thrown
	 * @return a ModelAndView to render the response
	 */
	private ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
			throws Exception {
		Method handler = getExceptionHandler(t);
		if (handler != null) {
			return invokeExceptionHandler(handler, request, response, t);
		}
		// If we get here, there was no custom handler
		if (t instanceof Exception) {
			throw (Exception) t;
		}
		if (t instanceof Error) {
			throw (Error) t;
		}
		// Shouldn't happen
		throw new ServletException("Unknown Throwable type encountered: " + t);
	}

	/**
	 * Create a new command object of the given class.
	 * Subclasses can override this implementation if they want.
	 * This implementation uses class.newInstance(), so commands need to have
	 * public no arg constructors.
	 */
	protected Object newCommandObject(Class clazz) throws ServletException {
		if (logger.isDebugEnabled()) {
			logger.debug("Must create new command of class [" + clazz.getName() + "]");
		}
		try {
			return clazz.newInstance();
		}
		catch (Exception ex) {
			throw new ServletException("Cannot instantiate command of class [" + clazz.getName() +
			                           "]: Does it have a public no arg constructor?", ex);
		}
	}
	
	/**
	 * Bind request parameters onto the given command bean
	 * @param request request from which parameters will be bound
	 * @param command command object, that must be a JavaBean
	 */
	protected void bind(ServletRequest request, Object command) throws ServletException {
		logger.debug("Binding request parameters onto command");
		ServletRequestDataBinder binder = new ServletRequestDataBinder(command, "command");
		binder.bind(request);
		binder.closeNoCatch();
	}
	
	/**
	 * Can return null if not found.
	 * @return a handler for the given exception type
	 * @param exception Won't be a ServletException or IOException
	 */
	protected Method getExceptionHandler(Throwable exception) {
		Class exceptionClass = exception.getClass();
		if (logger.isInfoEnabled()) {
			logger.info("Trying to find handler for exception class [" + exceptionClass.getName() + "]");
		}
		Method handler = (Method) this.exceptionHandlerHash.get(exceptionClass);
		while (handler == null && !exceptionClass.equals(Throwable.class)) {
			if (logger.isInfoEnabled()) {
				logger.info("Trying to find handler for exception superclass [" + exceptionClass.getName() + "]");
			}
			exceptionClass = exceptionClass.getSuperclass();
			handler = (Method) this.exceptionHandlerHash.get(exceptionClass);
		}
		return handler;
	}

	/**
	 * Invoke the selected exception handler.
	 * @param handler handler method to invoke
	 */
	private ModelAndView invokeExceptionHandler(Method handler, HttpServletRequest request,
																							HttpServletResponse response, Throwable ex) throws Exception {
		if (handler == null) {
			throw new ServletException("No handler for exception", ex);
		}

		// If we get here, we have a handler.
		if (logger.isInfoEnabled()) {
			logger.info("Invoking exception handler [" + handler + "] for exception [" + ex + "]");
		}
		try {
			ModelAndView mv = (ModelAndView) handler.invoke(this.delegate, new Object[] {request, response, ex});
			return mv;
		}
		catch (InvocationTargetException ex2) {
			Throwable targetEx = ex2.getTargetException();
			if (targetEx instanceof Exception) {
				throw (Exception) targetEx;
			}
			if (targetEx instanceof Error) {
				throw (Error) targetEx;
			}
			// shouldn't happen
			throw new ServletException("Unknown Throwable type encountered", targetEx);
		}
	}
	
}

⌨️ 快捷键说明

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