📄 velocityservlet.java
字号:
package org.apache.velocity.servlet;
/*
* Copyright 2000-2001,2004 The Apache Software Foundation.
*
* Licensed 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.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.OutputStreamWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.util.SimplePool;
import org.apache.velocity.context.Context;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;
/**
* Base class which simplifies the use of Velocity with Servlets.
* Extend this class, implement the <code>handleRequest()</code> method,
* and add your data to the context. Then call
* <code>getTemplate("myTemplate.wm")</code>.
*
* This class puts some things into the context object that you should
* be aware of:
* <pre>
* "req" - The HttpServletRequest object
* "res" - The HttpServletResponse object
* </pre>
*
* There are other methods you can override to access, alter or control
* any part of the request processing chain. Please see the javadocs for
* more information on :
* <ul>
* <li> loadConfiguration() : for setting up the Velocity runtime
* <li> createContext() : for creating and loading the Context
* <li> setContentType() : for changing the content type on a request
* by request basis
* <li> handleRequest() : you <b>must</b> implement this
* <li> mergeTemplate() : the template rendering process
* <li> requestCleanup() : post rendering resource or other cleanup
* <li> error() : error handling
* </ul>
* <br>
* If you put a contentType object into the context within either your
* serlvet or within your template, then that will be used to override
* the default content type specified in the properties file.
*
* "contentType" - The value for the Content-Type: header
*
* @author Dave Bryson
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="kjohnson@transparent.com">Kent Johnson</a>
* @author <a href="dlr@finemaltcoding.com">Daniel Rall</a>
* $Id: VelocityServlet.java,v 1.52.4.1 2004/03/03 23:23:03 geirm Exp $
*/
public abstract class VelocityServlet extends HttpServlet
{
/**
* The context key for the HTTP request object.
*/
public static final String REQUEST = "req";
/**
* The context key for the HTTP response object.
*/
public static final String RESPONSE = "res";
/**
* 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";
/**
* Encoding for the output stream
*/
public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1";
/**
* The default content type, itself defaulting to {@link
* #DEFAULT_CONTENT_TYPE} if not configured.
*/
private static String defaultContentType;
/**
* This is the string that is looked for when getInitParameter is
* called (<code>org.apache.velocity.properties</code>).
*/
protected static final String INIT_PROPS_KEY =
"org.apache.velocity.properties";
/**
* Use of this properties key has been deprecated, and will be
* removed in Velocity version 1.5.
*/
private static final String OLD_INIT_PROPS_KEY = "properties";
/**
* Cache of writers
*/
private static SimplePool writerPool = new SimplePool(40);
/**
* Performs initialization of this servlet. Called by the servlet
* container on loading.
*
* @param config The servlet configuration to apply.
*
* @exception ServletException
*/
public void init( ServletConfig config )
throws ServletException
{
super.init( config );
/*
* do whatever we have to do to init Velocity
*/
initVelocity( config );
/*
* Now that Velocity is initialized, cache some config.
*/
defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE,
DEFAULT_CONTENT_TYPE);
}
/**
* Initializes the Velocity runtime, first calling
* loadConfiguration(ServletConvig) to get a
* java.util.Properties of configuration information
* and then calling Velocity.init(). Override this
* to do anything to the environment before the
* initialization of the singelton takes place, or to
* initialize the singleton in other ways.
*/
protected void initVelocity( ServletConfig config )
throws ServletException
{
try
{
/*
* call the overridable method to allow the
* derived classes a shot at altering the configuration
* before initializing Runtime
*/
Properties props = loadConfiguration( config );
Velocity.init( props );
}
catch( Exception e )
{
throw new ServletException("Error initializing Velocity: " + e, e);
}
}
/**
* Loads the configuration information and returns that
* information as a Properties, which will be used to
* initialize the Velocity runtime.
* <br><br>
* Currently, this method gets the initialization parameter
* VelocityServlet.INIT_PROPS_KEY, which should be a file containing
* the configuration information.
* <br><br>
* To configure your Servlet Spec 2.2 compliant servlet runner to pass
* this to you, put the following in your WEB-INF/web.xml file
* <br>
* <pre>
* <servlet>
* <servlet-name> YourServlet </servlet-name>
* <servlet-class> your.package.YourServlet </servlet-class>
* <init-param>
* <param-name> org.apache.velocity.properties </param-name>
* <param-value> velocity.properties </param-value>
* </init-param>
* </servlet>
* </pre>
*
* Alternately, if you wish to configure an entire context in this
* fashion, you may use the following:
* <br>
* <pre>
* <context-param>
* <param-name> org.apache.velocity.properties </param-name>
* <param-value> velocity.properties </param-value>
* <description> Path to Velocity configuration </description>
* </context-param>
* </pre>
*
* Derived classes may do the same, or take advantage of this code to do the loading for them via :
* <pre>
* Properties p = super.loadConfiguration( config );
* </pre>
* and then add or modify the configuration values from the file.
* <br>
*
* @param config ServletConfig passed to the servlets init() function
* Can be used to access the real path via ServletContext (hint)
* @return java.util.Properties loaded with configuration values to be used
* to initialize the Velocity runtime.
* @throws FileNotFoundException if a specified file is not found.
* @throws IOException I/O problem accessing the specified file, if specified.
*/
protected Properties loadConfiguration(ServletConfig config)
throws IOException, FileNotFoundException
{
// This is a little overly complex because of legacy support
// for the initialization properties key "properties".
// References to OLD_INIT_PROPS_KEY should be removed at
// Velocity version 1.5.
String propsFile = config.getInitParameter(INIT_PROPS_KEY);
if (propsFile == null || propsFile.length() == 0)
{
ServletContext sc = config.getServletContext();
propsFile = config.getInitParameter(OLD_INIT_PROPS_KEY);
if (propsFile == null || propsFile.length() == 0)
{
propsFile = sc.getInitParameter(INIT_PROPS_KEY);
if (propsFile == null || propsFile.length() == 0)
{
propsFile = sc.getInitParameter(OLD_INIT_PROPS_KEY);
if (propsFile != null && propsFile.length() > 0)
{
sc.log("Use of the properties initialization " +
"parameter '" + OLD_INIT_PROPS_KEY + "' has " +
"been deprecated by '" + INIT_PROPS_KEY + '\'');
}
}
}
else
{
sc.log("Use of the properties initialization parameter '" +
OLD_INIT_PROPS_KEY + "' has been deprecated by '" +
INIT_PROPS_KEY + '\'');
}
}
/*
* This will attempt to find the location of the properties
* file from the relative path to the WAR archive (ie:
* docroot). Since JServ returns null for getRealPath()
* because it was never implemented correctly, then we know we
* will not have an issue with using it this way. I don't know
* if this will break other servlet engines, but it probably
* shouldn't since WAR files are the future anyways.
*/
Properties p = new Properties();
if ( propsFile != null )
{
String realPath = getServletContext().getRealPath(propsFile);
if ( realPath != null )
{
propsFile = realPath;
}
p.load( new FileInputStream(propsFile) );
}
return p;
}
/**
* Handles HTTP <code>GET</code> requests by calling {@link
* #doRequest()}.
*/
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles HTTP <code>POST</code> requests by calling {@link
* #doRequest()}.
*/
public void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles all requests (by default).
*
* @param request HttpServletRequest object containing client request
* @param response HttpServletResponse object for the response
*/
protected void doRequest(HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
Context context = null;
try
{
/*
* first, get a context
*/
context = createContext( request, response );
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -