📄 velocityviewservlet.java
字号:
package org.apache.velocity.tools.view.servlet;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.tools.generic.log.LogSystemCommonsLog;
import org.apache.velocity.tools.view.ToolboxManager;
import org.apache.velocity.tools.view.context.ChainedContext;
import org.apache.velocity.util.SimplePool;
/**
* <p>A servlet to process Velocity templates. This is comparable to the
* the JspServlet for JSP-based applications.</p>
*
* <p>The servlet provides the following features:</p>
* <ul>
* <li>renders Velocity templates</li>
* <li>provides support for an auto-loaded, configurable toolbox</li>
* <li>provides transparent access to the servlet request attributes,
* servlet session attributes and servlet context attributes by
* auto-searching them</li>
* <li>logs to the logging facility of the servlet API</li>
* </ul>
*
* <p>VelocityViewServlet supports the following configuration parameters
* in web.xml:</p>
* <dl>
* <dt>org.apache.velocity.toolbox</dt>
* <dd>Path and name of the toolbox configuration file. The path must be
* relative to the web application root directory. If this parameter is
* not found, the servlet will check for a toolbox file at
* '/WEB-INF/toolbox.xml'.</dd>
* <dt>org.apache.velocity.properties</dt>
* <dd>Path and name of the Velocity configuration file. The path must be
* relative to the web application root directory. If this parameter
* is not present, Velocity will check for a properties file at
* '/WEB-INF/velocity.properties'. If no file is found there, then
* Velocity is initialized with the settings in the classpath at
* 'org.apache.velocity.tools.view.servlet.velocity.properties'.</dd>
* </dl>
*
* <p>There are methods you may wish to override to access, alter or control
* any part of the request processing chain. Please see the javadocs for
* more information on :
* <ul>
* <li> {@link #loadConfiguration} : <br>for loading Velocity properties and
* configuring the Velocity runtime
* <li> {@link #setContentType} : <br>for changing the content type on a request
* by request basis
* <li> {@link #requestCleanup} : <br>post rendering resource or other cleanup
* <li> {@link #error} : <br>error handling
* </ul>
* </p>
*
* @author Dave Bryson
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:sidler@teamup.com">Gabe Sidler</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="mailto:kjohnson@transparent.com">Kent Johnson</a>
* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
* @author Nathan Bubna
*
* @version $Id: VelocityViewServlet.java 488468 2006-12-19 00:19:30Z nbubna $
*/
public class VelocityViewServlet extends HttpServlet
{
/** serial version id */
private static final long serialVersionUID = -3329444102562079189L;
/** The HTTP content type context key. */
public static final String CONTENT_TYPE = "default.contentType";
/** The default content type for the response */
public static final String DEFAULT_CONTENT_TYPE = "text/html";
/** Default encoding for the output stream */
public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1";
/**
* Key used to access the ServletContext in
* the Velocity application attributes.
*/
public static final String SERVLET_CONTEXT_KEY =
ServletContext.class.getName();
/**
* Default Runtime properties.
*/
public static final String DEFAULT_TOOLS_PROPERTIES =
"/org/apache/velocity/tools/view/servlet/velocity.properties";
/**
* Key used to access the toolbox configuration file path from the
* Servlet or webapp init parameters ("org.apache.velocity.toolbox").
*/
protected static final String TOOLBOX_KEY =
"org.apache.velocity.toolbox";
/**
* This is the string that is looked for when getInitParameter is
* called ("org.apache.velocity.properties").
*/
protected static final String INIT_PROPS_KEY =
"org.apache.velocity.properties";
/**
* Default toolbox configuration file path. If no alternate value for
* this is specified, the servlet will look here.
*/
protected static final String DEFAULT_TOOLBOX_PATH =
"/WEB-INF/toolbox.xml";
/**
* Default velocity properties file path. If no alternate value for
* this is specified, the servlet will look here.
*/
protected static final String DEFAULT_PROPERTIES_PATH =
"/WEB-INF/velocity.properties";
/** A reference to the toolbox manager. */
protected ToolboxManager toolboxManager = null;
/** Cache of writers */
private static SimplePool writerPool = new SimplePool(40);
/* The engine used to process templates. */
private VelocityEngine velocity = null;
/**
* The default content type. When necessary, includes the
* character set to use when encoding textual output.
*/
private String defaultContentType;
/**
* Whether we've logged a deprecation warning for
* ServletResponse's <code>getOutputStream()</code>.
* @since VelocityTools 1.1
*/
private boolean warnOfOutputStreamDeprecation = true;
/**
* <p>Initializes servlet, toolbox and Velocity template engine.
* Called by the servlet container on loading.</p>
*
* <p>NOTE: If no charset is specified in the default.contentType
* property (in your velocity.properties) and you have specified
* an output.encoding property, then that will be used as the
* charset for the default content-type of pages served by this
* servlet.</p>
*
* @param config servlet configuation
*/
public void init(ServletConfig config) throws ServletException
{
super.init(config);
// do whatever we have to do to init Velocity
initVelocity(config);
// init this servlet's toolbox (if any)
initToolbox(config);
// we can get these now that velocity is initialized
defaultContentType =
(String)getVelocityProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
String encoding =
(String)getVelocityProperty(RuntimeConstants.OUTPUT_ENCODING,
DEFAULT_OUTPUT_ENCODING);
// For non Latin-1 encodings, ensure that the charset is
// included in the Content-Type header.
if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding))
{
int index = defaultContentType.lastIndexOf("charset");
if (index < 0)
{
// the charset specifier is not yet present in header.
// append character encoding to default content-type
defaultContentType += "; charset=" + encoding;
}
else
{
// The user may have configuration issues.
velocity.warn("VelocityViewServlet: Charset was already " +
"specified in the Content-Type property. " +
"Output encoding property will be ignored.");
}
}
velocity.info("VelocityViewServlet: Default content-type is: " +
defaultContentType);
}
/**
* Looks up an init parameter with the specified key in either the
* ServletConfig or, failing that, in the ServletContext.
*/
protected String findInitParameter(ServletConfig config, String key)
{
// check the servlet config
String param = config.getInitParameter(key);
if (param == null || param.length() == 0)
{
// check the servlet context
ServletContext servletContext = config.getServletContext();
param = servletContext.getInitParameter(key);
}
return param;
}
/**
* Simplifies process of getting a property from VelocityEngine,
* because the VelocityEngine interface sucks compared to the singleton's.
* Use of this method assumes that {@link #initVelocity(ServletConfig)}
* has already been called.
*/
protected String getVelocityProperty(String key, String alternate)
{
String prop = (String)velocity.getProperty(key);
if (prop == null || prop.length() == 0)
{
return alternate;
}
return prop;
}
/**
* Returns the underlying VelocityEngine being used.
*/
protected VelocityEngine getVelocityEngine()
{
return velocity;
}
/**
* Sets the underlying VelocityEngine
*/
protected void setVelocityEngine(VelocityEngine ve)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -