📄 velocitycontroller.java
字号:
package dark.web.frame.velocity.controller;
/**
* <p>Title: 支持Velocity的控制器</p>
* <p>Description: 根据org.apache.velocity.servlet.VelocityViewServlet进行修改,
* 从而将Velocity整合进dwf框架</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: DIS</p>
* <p>Create Time: 2005-2-28 16:24:43</p>
* @author <a href="mailto:dark_he@hotmail.com">darkhe</a>
* @version 1.0
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dark.web.frame.Controller;
import dark.web.frame.Helper;
import dark.web.frame.controller.FrontController;
import dark.web.frame.velocity.command.VelocityCommand;
import dark.web.frame.velocity.form.VelocityForm;
import dark.web.frame.velocity.page.UnknownVelocityPage;
import dark.web.frame.velocity.page.VelocityPage;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.tools.view.ToolboxManager;
import org.apache.velocity.tools.view.servlet.ServletLogger;
import org.apache.velocity.tools.view.servlet.ServletToolboxManager;
import org.apache.velocity.tools.view.servlet.WebappLoader;
public abstract class VelocityController
extends FrontController
implements Controller
{
/** 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();
/**
* 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 =
"toolbox";
/**
* This is the string that is looked for when getInitParameter is
* called ("org.apache.velocity.properties").
*/
protected static final String INIT_PROPS_KEY =
"velocity";
/** A reference to the toolbox manager. */
protected ToolboxManager toolboxManager = null;
/**
* The default content type. When necessary, includes the
* character set to use when encoding textual output.
*/
protected String defaultContentType;
/**
* <p>Initializes servlet, toolbox and Velocity template engine.
* Called by the servlet container on loading.</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 =
RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
String encoding =
RuntimeSingleton.getString(RuntimeSingleton.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("VelocityController: Charset was already " +
"specified in the Content-Type property. " +
"Output encoding property will be ignored.");
}
}
Velocity.info("VelocityController: Default content-type is: " +
defaultContentType);
}
/**
* Initializes the ServletToolboxManager for this servlet's
* toolbox (if any).
*
* @param config servlet configuation
*/
protected void initToolbox(ServletConfig config) throws ServletException
{
ServletContext servletContext = config.getServletContext();
/* check the servlet config for a toolbox */
String file = config.getInitParameter(TOOLBOX_KEY);
/* check the servlet context for a toolbox */
if (file == null || file.length() == 0)
{
file = servletContext.getInitParameter(TOOLBOX_KEY);
}
/* if we have a toolbox, get a manager for it */
if (file != null)
{
toolboxManager =
ServletToolboxManager.getInstance(servletContext, file);
}
else
{
Velocity.info("VelocityController: No toolbox entry in configuration.");
}
}
/**
* Initializes the Velocity runtime, first calling
* loadConfiguration(ServletConfig) to get a
* org.apache.commons.collections.ExtendedProperties
* of configuration information
* and then calling Velocity.init(). Override this
* to do anything to the environment before the
* initialization of the singleton takes place, or to
* initialize the singleton in other ways.
*
* @param config servlet configuration parameters
*/
protected void initVelocity(ServletConfig config) throws ServletException
{
Velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, getServletContext());
// default to servletlogger, which logs to the servlet engines log
Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
ServletLogger.class.getName());
// by default, load resources with webapp resource loader
Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "webapp");
Velocity.setProperty("webapp.resource.loader.class",
WebappLoader.class.getName());
try
{
InputStream is = Helper.getInputStream(config.getServletContext(), INIT_PROPS_KEY);
Properties p = new Properties();
p.load(is);
/*
* now, lets get the two elements we care about, the
* template path and the log, and fix those from relative
* to the webapp root, to absolute on the filesystem, which is
* what velocity needs
*/
String path = p.getProperty("file.resource.loader.path");
if (path != null)
{
path = getServletContext().getRealPath(path);
log.info("file.resource.loader.path=" + path);
p.setProperty("file.resource.loader.path", path);
}
path = p.getProperty("runtime.log");
if (path != null)
{
path = getServletContext().getRealPath(path);
log.info("runtime.log=" + path);
p.setProperty("runtime.log", path);
}
Velocity.init(p);
log.info("初始化Velocity引擎成功......");
}
catch (IOException e)
{
log.error("初始化Velocity引擎出错", e);
}
catch (Exception e)
{
log.error("初始化Velocity引擎出错", e);
}
}
/**
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @see dark.web.frame.Controller#doRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doRequest(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 获取page.postfix和command.postfix
// 从而根据用户的请求后缀的不同调用页面处理程序或者命令处理程序
String page_postfix = configuration.getString("page.postfix");
String command_postfix = configuration.getString("command.postfix");
if (page_postfix.equals(getRequestPostfix(request)))
// 调用页面处理程序
{
String uri = request.getRequestURI();
VelocityPage page = getVelocityPage((HttpServletRequest) request);
// 初始化页面类
page.init(
getServletContext(),
getServletConfig(),
request,
response);
// 设置velocity模版
page.setTarget(uri);
// 检证页面类的执行权限
if (page.isAuthentic())
{
// 执行真实的商业逻辑
page.process();
}
}
else if (command_postfix.equals(getRequestPostfix(request)))
// 调用命令处理程序
{
// 如果要求做表单验证,则处理之
if (isValidate(request))
{
String input = getInput(request);
// 如果用户没有指定请求转发路径,则指定default value
if (input.equals(""))
{
input = configuration.getString("default.input");
log.warn(
"dont't specify parameter $INPUT, use default.input:"
+ input);
request.setAttribute(
"$WARM",
"dont't specify parameter $INPUT, use default.input"
+ input);
}
VelocityForm form = getVelocityForm(request);
// 初始化表单验证类
form.init(getServletContext(), request, response, getMessage());
// 设置default的ContentType
form.setContentType(defaultContentType);
// 设置defautl的OutputEncoding
form.setOutputEncoding(DEFAULT_OUTPUT_ENCODING);
// 传入toolboxManager
form.setToolboxManager(toolboxManager);
// 设置当前表单验证的用户请求转发路径
form.setInput(input);
// 检证表单验证类的执行权限
if (form.isAuthentic())
{
// 执行实际的验证操作
form.validate(request, response);
if (!form.isPass())
{
// 如果isPass()返回false,
// 则说明验证出表单错误,
// 立即停止程序处理
//log.debug("表单验证失败");
return;
}
//log.debug("表单验证成功");
//log.debug("form.isPass()=" + form.isPass());
}
}
String target = getTarget(request);
// 如果用户没有指定请求转发路径,则指定default value
if (target.equals(""))
{
target = configuration.getString("default.target");
log.warn(
"don't specify paramter $TARGER, use default.target:"
+ target);
request.setAttribute(
"$WARM",
"don't specify paramter $TARGER, use default.target:"
+ target);
}
VelocityCommand command = getVelocityCommand(request);
// 初始化命令类
command.init(
getServletContext(),
getServletConfig(),
request,
response);
// 设置default的ContentType
command.setContentType(defaultContentType);
// 设置defautl的OutputEncoding
command.setOutputEncoding(DEFAULT_OUTPUT_ENCODING);
// 传入toolboxManager
command.setToolboxManager(toolboxManager);
// 设置当前命令的用户请求转发路径
command.setTarget(target);
// 检证命令类的执行权限
if (command.isAuthentic())
{
// 执行真实的商业逻辑
command.process();
}
}
}
/**
* @param request
* @return
*/
protected VelocityForm getVelocityForm(HttpServletRequest request)
throws ServletException
{
try
{
return (VelocityForm) getFormClass(request).newInstance();
}
catch (Exception e)
{
throw new ServletException(e);
}
}
/**
* @param req
* @return
*/
protected VelocityCommand getVelocityCommand(HttpServletRequest request)
throws ServletException
{
try
{
return (VelocityCommand) getCommandClass(request).newInstance();
}
catch (Exception e)
{
throw new ServletException(e);
}
}
/**
* @param request
* @return
*/
protected VelocityPage getVelocityPage(HttpServletRequest request)
throws ServletException
{
try
{
return (VelocityPage) getVelocityPageClass(request).newInstance();
}
catch (Exception e)
{
throw new ServletException(e);
}
}
/**
* 通过类名串值到得类对象
* @param req
*/
protected Class getVelocityPageClass(HttpServletRequest request)
{
Class result = null;
String cp = configuration.getString("page.package");
String pageName = getPageName(request);
String pageClassName = cp + "." + pageName;
try
{
result = Class.forName(pageClassName);
}
catch (ClassNotFoundException e)
{
log.info(
"class:"
+ pageClassName
+ " not found, return UnknownVelocityPage.class");
result = UnknownVelocityPage.class;
}
return result;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -