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

📄 velocityview.java

📁 spring的源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

	/**
	 * Process the model map by merging it with the Velocity template.
	 * Output is directed to the servlet response.
	 * <p>This method can be overridden if custom behavior is needed.
	 */
	protected void renderMergedTemplateModel(
			Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		response.setContentType(getContentType());
		exposeHelpers(model, request);

		// create Velocity Context from model
		Context velocityContext = createVelocityContext(model, request, response);

		exposeHelpers(velocityContext, request, response);
		exposeToolAttributes(velocityContext, request);

		doRender(velocityContext, response);
	}

	/**
	 * Expose helpers unique to each rendering operation. This is necessary so that
	 * different rendering operations can't overwrite each other's formats etc.
	 * <p>Called by <code>renderMergedTemplateModel</code>. The default implementation
	 * is empty. This method can be overridden to add custom helpers to the model.
	 * @param model the model that will be passed to the template for merging
	 * @param request current HTTP request
	 * @throws Exception if there's a fatal error while we're adding model attributes
	 * @see #renderMergedTemplateModel
	 */
	protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
	}

	/**
	 * Create a Velocity Context instance for the given model,
	 * to be passed to the template for merging.
	 * <p>Default implementation delegates to <code>createVelocityContext(model)</code>.
	 * Can be overridden for a special context class, for example ChainedContext which
	 * is part of the view package of Velocity Tools. ChainedContext is needed for
	 * initialization of ViewTool instances.
	 * <p>Have a look at VelocityToolboxView, which pre-implements such a ViewTool
	 * check. This is not part of the standard VelocityView class to avoid a
	 * required dependency on the view package of Velocity Tools.
	 * @param model the model Map, containing the model attributes
	 * to be exposed to the view
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @return the Velocity Context
	 * @throws Exception if there's a fatal error while creating the context
	 * @see #createVelocityContext(Map)
	 * @see org.apache.velocity.tools.view.context.ChainedContext
	 * @see org.apache.velocity.tools.view.tools.ViewTool
	 * @see #initTool
	 * @see VelocityToolboxView
	 */
	protected Context createVelocityContext(
			Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		return createVelocityContext(model);
	}

	/**
	 * Create a Velocity Context instance for the given model,
	 * to be passed to the template for merging.
	 * <p>Default implementation creates an instance of Velocity's
	 * VelocityContext implementation class.
	 * @param model the model Map, containing the model attributes
	 * to be exposed to the view
	 * @return the Velocity Context
	 * @throws Exception if there's a fatal error while creating the context
	 * @see org.apache.velocity.VelocityContext
	 */
	protected Context createVelocityContext(Map model) throws Exception {
		return new VelocityContext(model);
	}

	/**
	 * Expose helpers unique to each rendering operation. This is necessary so that
	 * different rendering operations can't overwrite each other's formats etc.
	 * <p>Called by <code>renderMergedTemplateModel</code>. Default implementation
	 * delegates to <code>exposeHelpers(velocityContext, request)</code>. This method
	 * can be overridden to add special tools to the context, needing the servlet response
	 * to initialize (see Velocity Tools, for example LinkTool and ViewTool/ChainedContext).
	 * @param velocityContext Velocity context that will be passed to the template
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @throws Exception if there's a fatal error while we're adding model attributes
	 * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest)
	 */
	protected void exposeHelpers(
			Context velocityContext, HttpServletRequest request, HttpServletResponse response) throws Exception {

		exposeHelpers(velocityContext, request);
	}

	/**
	 * Expose helpers unique to each rendering operation. This is necessary so that
	 * different rendering operations can't overwrite each other's formats etc.
	 * <p>Default implementation is empty. This method can be overridden to add
	 * custom helpers to the Velocity context.
	 * @param velocityContext Velocity context that will be passed to the template
	 * @param request current HTTP request
	 * @throws Exception if there's a fatal error while we're adding model attributes
	 * @see #exposeHelpers(Map, HttpServletRequest)
	 */
	protected void exposeHelpers(Context velocityContext, HttpServletRequest request) throws Exception {
	}

	/**
	 * Expose the tool attributes, according to corresponding bean property settings.
	 * <p>Do not override this method unless for further tools driven by bean properties.
	 * Override one of the <code>exposeHelpers</code> methods to add custom helpers.
	 * @param velocityContext Velocity context that will be passed to the template
	 * @param request current HTTP request
	 * @throws Exception if there's a fatal error while we're adding model attributes
	 * @see #setVelocityFormatterAttribute
	 * @see #setDateToolAttribute
	 * @see #setNumberToolAttribute
	 * @see #exposeHelpers(Map, HttpServletRequest)
	 * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)
	 */
	protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
		// Expose generic attributes.
		if (this.toolAttributes != null) {
			for (Iterator it = this.toolAttributes.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				String attributeName = (String) entry.getKey();
				Class toolClass = (Class) entry.getValue();
				try {
					Object tool = toolClass.newInstance();
					initTool(tool, velocityContext);
					velocityContext.put(attributeName, tool);
				}
				catch (Exception ex) {
					throw new NestedServletException("Could not instantiate Velocity tool '" + attributeName + "'", ex);
				}
			}
		}

		// Expose VelocityFormatter attribute.
		if (this.velocityFormatterAttribute != null) {
			velocityContext.put(this.velocityFormatterAttribute, new VelocityFormatter(velocityContext));
		}

		// Expose locale-aware DateTool/NumberTool attributes.
		if (this.dateToolAttribute != null || this.numberToolAttribute != null) {
			Locale locale = RequestContextUtils.getLocale(request);
			if (this.dateToolAttribute != null) {
				velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(locale));
			}
			if (this.numberToolAttribute != null) {
				velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(locale));
			}
		}
	}

	/**
	 * Initialize the given tool instance. The default implementation is empty.
	 * <p>Can be overridden to check for special callback interfaces, for example
	 * the ViewContext interface which is part of the view package of Velocity Tools.
	 * In the particular case of ViewContext, you'll usually also need a special
	 * Velocity context, like ChainedContext which is part of Velocity Tools too.
	 * <p>Have a look at VelocityToolboxView, which pre-implements such a ViewTool
	 * check. This is not part of the standard VelocityView class to avoid a
	 * required dependency on the view package of Velocity Tools.
	 * @param tool the tool instance to initialize
	 * @param velocityContext the Velocity context
	 * @throws Exception if initializion of the tool failed
	 * @see org.apache.velocity.tools.view.tools.ViewTool
	 * @see org.apache.velocity.tools.view.context.ChainedContext
	 * @see #createVelocityContext
	 * @see VelocityToolboxView
	 */
	protected void initTool(Object tool, Context velocityContext) throws Exception {
	}


	/**
	 * Render the Velocity view to the given response, using the given Velocity
	 * context which contains the complete template model to use.
	 * <p>The default implementation renders the template specified by the "url"
	 * bean property, retrieved via <code>getTemplate</code>. It delegates to the
	 * <code>mergeTemplate</code> method to merge the template instance with the
	 * given Velocity context.
	 * <p>Can be overridden to customize the behavior, for example to render
	 * multiple templates into a single view.
	 * @param context the Velocity context to use for rendering
	 * @param response servlet response (use this to get the OutputStream or Writer)
	 * @throws Exception if thrown by Velocity
	 * @see #setUrl
	 * @see #getTemplate()
	 * @see #mergeTemplate
	 */
	protected void doRender(Context context, HttpServletResponse response) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Rendering Velocity template [" + getUrl() + "] in VelocityView '" + getBeanName() + "'");
		}
		mergeTemplate(getTemplate(), context, response);
	}

	/**
	 * Retrieve the Velocity template to be rendered by this view.
	 * <p>By default, the template specified by the "url" bean property will be
	 * retrieved: either returning a cached template instance or loading a fresh
	 * instance (according to the "cacheTemplate" bean property)
	 * @return the Velocity template to render
	 * @throws Exception if thrown by Velocity
	 * @see #setUrl
	 * @see #setCacheTemplate
	 * @see #getTemplate(String)
	 */
	protected Template getTemplate() throws Exception {
		// We already hold a reference to the template, but we might want to load it
		// if not caching. Velocity itself caches templates, so our ability to
		// cache templates in this class is a minor optimization only.
		if (isCacheTemplate() && this.template != null) {
			return this.template;
		}
		else {
			return getTemplate(getUrl());
		}
	}

	/**
	 * Retrieve the Velocity template specified by the given name,
	 * using the encoding specified by the "encoding" bean property.
	 * <p>Can be called by subclasses to retrieve a specific template,
	 * for example to render multiple templates into a single view.
	 * @param name the file name of the desired template
	 * @return the Velocity template
	 * @throws Exception if thrown by Velocity
	 * @see org.apache.velocity.app.VelocityEngine#getTemplate
	 */
	protected Template getTemplate(String name) throws Exception {
		return (getEncoding() != null ?
				getVelocityEngine().getTemplate(name, getEncoding()) :
				getVelocityEngine().getTemplate(name));
	}

	/**
	 * Merge the template with the context.
	 * Can be overridden to customize the behavior.
	 * @param template the template to merge
	 * @param context the Velocity context to use for rendering
	 * @param response servlet response (use this to get the OutputStream or Writer)
	 * @throws Exception if thrown by Velocity
	 * @see org.apache.velocity.Template#merge
	 */
	protected void mergeTemplate(
			Template template, Context context, HttpServletResponse response) throws Exception {

		try {
			template.merge(context, response.getWriter());
		}
		catch (MethodInvocationException ex) {
			throw new NestedServletException(
					"Method invocation failed during rendering of Velocity view with name '" +
					getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
					"], method '" + ex.getMethodName() + "'",
					ex.getWrappedThrowable());
		}
	}


	/**
	 * Subclass of DateTool from Velocity Tools, using a passed-in Locale
	 * (usually the RequestContext Locale) instead of the default Locale.N
	 * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
	 */
	private static class LocaleAwareDateTool extends DateTool {

		private final Locale locale;

		private LocaleAwareDateTool(Locale locale) {
			this.locale = locale;
		}

		public Locale getLocale() {
			return this.locale;
		}
	}


	/**
	 * Subclass of NumberTool from Velocity Tools, using a passed-in Locale
	 * (usually the RequestContext Locale) instead of the default Locale.
	 * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
	 */
	private static class LocaleAwareNumberTool extends NumberTool {

		private final Locale locale;

		private LocaleAwareNumberTool(Locale locale) {
			this.locale = locale;
		}

		public Locale getLocale() {
			return this.locale;
		}
	}

}

⌨️ 快捷键说明

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