1/*2 * $Id: VelocityRenderer.java 1306435 2012-03-28 15:39:11Z nlebas $3 *4 * Licensed to the Apache Software Foundation (ASF) under one5 * or more contributor license agreements. See the NOTICE file6 * distributed with this work for additional information7 * regarding copyright ownership. The ASF licenses this file8 * to you under the Apache License, Version 2.0 (the9 * "License"); you may not use this file except in compliance10 * with the License. You may obtain a copy of the License at11 *12 * http://www.apache.org/licenses/LICENSE-2.013 *14 * Unless required by applicable law or agreed to in writing,15 * software distributed under the License is distributed on an16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY17 * KIND, either express or implied. See the License for the18 * specific language governing permissions and limitations19 * under the License.20 */2122package org.apache.tiles.request.velocity.render;
2324import java.io.IOException;
2526import org.apache.tiles.request.Request;
27import org.apache.tiles.request.render.CannotRenderException;
28import org.apache.tiles.request.render.Renderer;
29import org.apache.tiles.request.servlet.ServletRequest;
30import org.apache.tiles.request.servlet.ServletUtil;
31import org.apache.velocity.Template;
32import org.apache.velocity.context.Context;
33import org.apache.velocity.tools.view.VelocityView;
3435/**36 * Attribute renderer for rendering Velocity templates as attributes. <br>37 * It is available only to Servlet-based environment.<br>38 * It uses {@link VelocityView} to render the response.<br>39 * To initialize it correctly, call {@link #setParameter(String, String)} for40 * all the parameters that you want to set, and then call {@link #commit()}.41 *42 * @version $Rev: 1306435 $ $Date: 2012-03-29 02:39:11 +1100 (Thu, 29 Mar 2012) $43 */44publicclassVelocityRendererimplementsRenderer {
4546/**47 * The VelocityView object to use.48 */49private VelocityView velocityView;
5051/**52 * Constructor.53 *54 * @param velocityView The Velocity view manager.55 */56publicVelocityRenderer(VelocityView velocityView) {
57this.velocityView = velocityView;
58 }
5960/** {@inheritDoc} */61 @Override
62publicvoid render(String path, Request request) throws IOException {
63if (path == null) {
64thrownewCannotRenderException("Cannot dispatch a null path");
65 }
6667ServletRequest servletRequest = ServletUtil.getServletRequest(request);
68// then get a context69 Context context = velocityView.createContext(servletRequest
70 .getRequest(), servletRequest.getResponse());
7172// get the template73 Template template = velocityView.getTemplate((String) path);
7475// merge the template and context into the writer76 velocityView.merge(template, context, request.getWriter());
77 }
7879/** {@inheritDoc} */80publicboolean isRenderable(String path, Request request) {
81return path != null && path.startsWith("/") && path.endsWith(".vm");
82 }
83 }