本站首页    管理页面    写新日志    退出

«September 2025»
123456
78910111213
14151617181920
21222324252627
282930


公告

  如果你忍了,欺负你的人将来可能就进监狱了。如果你反击,欺负你的人将来可能就获选十大杰出青年了。

        QQ: 3159671

http://greenboy.javaeye.com/

http://blog.sina.com.cn/u/1278341164 小鸟吹烟


我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:小鸟吹烟
日志总数:157
评论数量:424
留言数量:-1
访问次数:1260230
建立时间:2006年10月23日




[SSH 学习区]ActionServlet
文章收藏,  网上资源

tone 发表于 2007/3/12 16:58:40

  package org.apache.struts.action;import java.io.IOException;import java.io.InputStream;import java.math.BigDecimal;import java.math.BigInteger;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.Enumeration;import java.util.Iterator;import java.util.MissingResourceException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.UnavailableException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.sql.DataSource;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.PropertyUtils;import org.apache.commons.beanutils.converters.BigDecimalConverter;import org.apache.commons.beanutils.converters.BigIntegerConverter;import org.apache.commons.beanutils.converters.BooleanConverter;import org.apache.commons.beanutils.converters.ByteConverter;import org.apache.commons.beanutils.converters.CharacterConverter;import org.apache.commons.beanutils.converters.DoubleConverter;import org.apache.commons.beanutils.converters.FloatConverter;import org.apache.commons.beanutils.converters.IntegerConverter;import org.apache.commons.beanutils.converters.LongConverter;import org.apache.commons.beanutils.converters.ShortConverter;import org.apache.commons.collections.FastHashMap;import org.apache.commons.digester.Digester;import org.apache.commons.digester.RuleSet;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.struts.Globals;import org.apache.struts.config.ConfigRuleSet;import org.apache.struts.config.DataSourceConfig;import org.apache.struts.config.FormBeanConfig;import org.apache.struts.config.MessageResourcesConfig;import org.apache.struts.config.ModuleConfig;import org.apache.struts.config.ModuleConfigFactory;import org.apache.struts.config.PlugInConfig;import org.apache.struts.util.MessageResources;import org.apache.struts.util.MessageResourcesFactory;import org.apache.struts.util.ModuleUtils;import org.apache.struts.util.RequestUtils;import org.apache.struts.util.ServletContextWriter;import org.xml.sax.InputSource;import org.xml.sax.SAXException;/*** Title:<br>* Description:<br>* Copyright: Copyright (c) 2006<br>* Company: <br>* @author * @version  */public class ActionServlet extends HttpServlet {protected String config = "/WEB-INF/struts-config.xml";protected Digester configDigester = null;protected boolean convertNull = false;protected FastHashMap dataSources = new FastHashMap();protected MessageResources internal = null;protected String internalName = "org.apache.struts.action.ActionResources";protected static Log log = LogFactory.getLog(ActionServlet.class);protected RequestProcessor processor = null;protected String registrations[] ={"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN","/org/apache/struts/resources/struts-config_1_0.dtd","-//Apache Software Foundation//DTD Struts Configuration 1.1//EN","/org/apache/struts/resources/struts-config_1_1.dtd","-//Apache Software Foundation//DTD Struts Configuration 1.2//EN","/org/apache/struts/resources/struts-config_1_2.dtd","-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN","/org/apache/struts/resources/web-app_2_2.dtd","-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN","/org/apache/struts/resources/web-app_2_3.dtd" };protected String servletMapping = null;protected String servletName = null;/** * 销毁<br>* ==>>销毁所有模板<br>* ==>>[internal = null]<br>* ==>>销毁上下文属性[org.apache.struts.action.ACTION_SERVLET]* ==>>终结日志工厂<br>*/public void destroy() {if (log.isDebugEnabled()) {log.debug(internal.getMessage("finalizing"));}destroyModules();destroyInternal();getServletContext().removeAttribute(Globals.ACTION_SERVLET_KEY);ClassLoader classLoader = Thread.currentThread().getContextClassLoader();if (classLoader == null) {classLoader = ActionServlet.class.getClassLoader();}try {LogFactory.release(classLoader);} catch (Throwable t) {}PropertyUtils.clearDescriptors();}/** * 初始化<br>* ==>>加载org.apache.struts.util.PropertyMessageResourcesFactory并实例化<br>* ==>>从web.xml中获得struts配置文件<br>* ==>>从web.mxl到org.apache.struts.action.ActionServlet的映射处理<br>* ==>>把ActionServlet放入上下文<br>* ==>>初始化[资源读取工厂类]<br>* ==>>初始化[数据源]<br>* ==>>初始化[插件]<br>* ==>>冻结已经读取的资源<br>* ==>>递归初始化配置文件<br>* @throws ServletException*/public void init() throws ServletException {try {initInternal();initOther();initServlet();getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);initModuleConfigFactory();ModuleConfig moduleConfig = initModuleConfig("", config);initModuleMessageResources(moduleConfig);initModuleDataSources(moduleConfig);initModulePlugIns(moduleConfig);moduleConfig.freeze();Enumeration names = getServletConfig().getInitParameterNames();while (names.hasMoreElements()) {String name = (String) names.nextElement();if (!name.startsWith("config/")) {continue;}String prefix = name.substring(6);moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name));initModuleMessageResources(moduleConfig);initModuleDataSources(moduleConfig);initModulePlugIns(moduleConfig);moduleConfig.freeze();}this.initModulePrefixes(this.getServletContext());this.destroyConfigDigester();} catch (UnavailableException ex) {throw ex;} catch (Throwable t) {log.error("Unable to initialize Struts ActionServlet due to an "+ "unexpected exception or error thrown, so marking the "+ "servlet as unavailable.  Most likely, this is due to an "+ "incorrect or missing library dependency.",t);throw new UnavailableException(t.getMessage());}}protected void initModulePrefixes(ServletContext context) {ArrayList prefixList = new ArrayList();Enumeration names = context.getAttributeNames();while (names.hasMoreElements()) {String name = (String) names.nextElement();if (!name.startsWith(Globals.MODULE_KEY)) {continue;}String prefix = name.substring(Globals.MODULE_KEY.length());if (prefix.length() > 0) {prefixList.add(prefix);}}String[] prefixes = (String[]) prefixList.toArray(new String[prefixList.size()]);context.setAttribute(Globals.MODULE_PREFIXES_KEY, prefixes);}public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {process(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {process(request, response);}public void addServletMapping(String servletName, String urlPattern) {if (log.isDebugEnabled()) {log.debug("Process servletName=" + servletName + ", urlPattern=" + urlPattern);}if (servletName == null) {return;}if (servletName.equals(this.servletName)) {this.servletMapping = urlPattern;}}public MessageResources getInternal() {return (this.internal);}/** * 销毁所有模板<br>*/protected void destroyModules() {ArrayList values = new ArrayList();Enumeration names = getServletContext().getAttributeNames();while (names.hasMoreElements()) {values.add(names.nextElement());}Iterator keys = values.iterator();while (keys.hasNext()) {String name = (String) keys.next();Object value = getServletContext().getAttribute(name);if (!(value instanceof ModuleConfig)) {continue;}ModuleConfig config = (ModuleConfig) value;if (this.getProcessorForModule(config) != null) {this.getProcessorForModule(config).destroy();}getServletContext().removeAttribute(name);PlugIn plugIns[] = (PlugIn[]) getServletContext().getAttribute(Globals.PLUG_INS_KEY + config.getPrefix());if (plugIns != null) {for (int i = 0; i < plugIns.length; i++) {int j = plugIns.length - (i + 1);plugIns[j].destroy();}getServletContext().removeAttribute(Globals.PLUG_INS_KEY + config.getPrefix());}}}protected void destroyConfigDigester() {configDigester = null;}protected void destroyInternal() {internal = null;}protected ModuleConfig getModuleConfig(HttpServletRequest request) {ModuleConfig config = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);if (config == null) {config = (ModuleConfig) getServletContext().getAttribute(Globals.MODULE_KEY);}return (config);}protected synchronized RequestProcessor getRequestProcessor(ModuleConfig config) throws ServletException {RequestProcessor processor = this.getProcessorForModule(config);if (processor == null) {try {processor =(RequestProcessor) RequestUtils.applicationInstance(config.getControllerConfig().getProcessorClass());} catch (Exception e) {throw new UnavailableException("Cannot initialize RequestProcessor of class "+ config.getControllerConfig().getProcessorClass()+ ": "+ e);}processor.init(this, config);String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();getServletContext().setAttribute(key, processor);}return (processor);}private RequestProcessor getProcessorForModule(ModuleConfig config) {String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();return (RequestProcessor) getServletContext().getAttribute(key);}protected void initModuleConfigFactory() {String configFactory = getServletConfig().getInitParameter("configFactory");if (configFactory != null) {ModuleConfigFactory.setFactoryClass(configFactory);}}protected ModuleConfig initModuleConfig(String prefix, String paths) throws ServletException {if (log.isDebugEnabled()) {log.debug("Initializing module path '" + prefix + "' configuration from '" + paths + "'");}ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();ModuleConfig config = factoryObject.createModuleConfig(prefix);Digester digester = initConfigDigester();while (paths.length() > 0) {digester.push(config);String path = null;int comma = paths.indexOf(',');if (comma >= 0) {path = paths.substring(0, comma).trim();paths = paths.substring(comma + 1);} else {path = paths.trim();paths = "";}if (path.length() < 1) {break;}this.parseModuleConfigFile(digester, path);}getServletContext().setAttribute(Globals.MODULE_KEY + config.getPrefix(), config);FormBeanConfig fbs[] = config.findFormBeanConfigs();for (int i = 0; i < fbs.length; i++) {if (fbs[i].getDynamic()) {fbs[i].getDynaActionFormClass();}}return config;}protected void parseModuleConfigFile(Digester digester, String path) throws UnavailableException {InputStream input = null;try {URL url = getServletContext().getResource(path);if (url == null) {url = getClass().getResource(path);}if (url == null) {String msg = internal.getMessage("configMissing", path);log.error(msg);throw new UnavailableException(msg);}InputSource is = new InputSource(url.toExternalForm());input = url.openStream();is.setByteStream(input);digester.parse(is);} catch (MalformedURLException e) {handleConfigException(path, e);} catch (IOException e) {handleConfigException(path, e);} catch (SAXException e) {handleConfigException(path, e);} finally {if (input != null) {try {input.close();} catch (IOException e) {throw new UnavailableException(e.getMessage());}}}}private void handleConfigException(String path, Exception e) throws UnavailableException {String msg = internal.getMessage("configParse", path);log.error(msg, e);throw new UnavailableException(msg);}/** * <br>* @param ModuleConfig config* @throws ServletException*/protected void initModuleDataSources(ModuleConfig config) throws ServletException {if (log.isDebugEnabled()) {log.debug("Initializing module path '" + config.getPrefix() + "' data sources");}ServletContextWriter scw = new ServletContextWriter(getServletContext());DataSourceConfig dscs[] = config.findDataSourceConfigs();if (dscs == null) {dscs = new DataSourceConfig[0];}dataSources.setFast(false);for (int i = 0; i < dscs.length; i++) {if (log.isDebugEnabled()) {log.debug("Initializing module path '" + config.getPrefix() + "' data source '" + dscs[i].getKey() + "'");}DataSource ds = null;try {ds = (DataSource) RequestUtils.applicationInstance(dscs[i].getType());BeanUtils.populate(ds, dscs[i].getProperties());ds.setLogWriter(scw);} catch (Exception e) {log.error(internal.getMessage("dataSource.init", dscs[i].getKey()), e);throw new UnavailableException(internal.getMessage("dataSource.init", dscs[i].getKey()));}getServletContext().setAttribute(dscs[i].getKey() + config.getPrefix(), ds);dataSources.put(dscs[i].getKey(), ds);}dataSources.setFast(true);}protected void initModulePlugIns(ModuleConfig config) throws ServletException {if (log.isDebugEnabled()) {log.debug("Initializing module path '" + config.getPrefix() + "' plug ins");}PlugInConfig plugInConfigs[] = config.findPlugInConfigs();PlugIn plugIns[] = new PlugIn[plugInConfigs.length];getServletContext().setAttribute(Globals.PLUG_INS_KEY + config.getPrefix(), plugIns);for (int i = 0; i < plugIns.length; i++) {try {plugIns[i] = (PlugIn) RequestUtils.applicationInstance(plugInConfigs[i].getClassName());BeanUtils.populate(plugIns[i], plugInConfigs[i].getProperties());try {PropertyUtils.setProperty(plugIns[i], "currentPlugInConfigObject", plugInConfigs[i]);} catch (Exception e) {}plugIns[i].init(this, config);} catch (ServletException e) {throw e;} catch (Exception e) {String errMsg = internal.getMessage("plugIn.init", plugInConfigs[i].getClassName());log(errMsg, e);throw new UnavailableException(errMsg);}}}protected void initModuleMessageResources(ModuleConfig config) throws ServletException {MessageResourcesConfig mrcs[] = config.findMessageResourcesConfigs();for (int i = 0; i < mrcs.length; i++) {if ((mrcs[i].getFactory() == null) || (mrcs[i].getParameter() == null)) {continue;}if (log.isDebugEnabled()) {log.debug("Initializing module path '"+ config.getPrefix()+ "' message resources from '"+ mrcs[i].getParameter()+ "'");}String factory = mrcs[i].getFactory();MessageResourcesFactory.setFactoryClass(factory);MessageResourcesFactory factoryObject = MessageResourcesFactory.createFactory();factoryObject.setConfig(mrcs[i]);MessageResources resources = factoryObject.createResources(mrcs[i].getParameter());resources.setReturnNull(mrcs[i].getNull());resources.setEscape(mrcs[i].isEscape());getServletContext().setAttribute(mrcs[i].getKey() + config.getPrefix(), resources);}}protected Digester initConfigDigester() throws ServletException {if (configDigester != null) {return (configDigester);}configDigester = new Digester();configDigester.setNamespaceAware(true);configDigester.setValidating(this.isValidating());configDigester.setUseContextClassLoader(true);configDigester.addRuleSet(new ConfigRuleSet());for (int i = 0; i < registrations.length; i += 2) {URL url = this.getClass().getResource(registrations[i + 1]);if (url != null) {configDigester.register(registrations[i], url.toString());}}this.addRuleSets();return (configDigester);}private void addRuleSets() throws ServletException {String rulesets = getServletConfig().getInitParameter("rulesets");if (rulesets == null) {rulesets = "";}rulesets = rulesets.trim();String ruleset = null;while (rulesets.length() > 0) {int comma = rulesets.indexOf(",");if (comma < 0) {ruleset = rulesets.trim();rulesets = "";} else {ruleset = rulesets.substring(0, comma).trim();rulesets = rulesets.substring(comma + 1).trim();}if (log.isDebugEnabled()) {log.debug("Configuring custom Digester Ruleset of type " + ruleset);}try {RuleSet instance = (RuleSet) RequestUtils.applicationInstance(ruleset);this.configDigester.addRuleSet(instance);} catch (Exception e) {log.error("Exception configuring custom Digester RuleSet", e);throw new ServletException(e);}}}private boolean isValidating() {boolean validating = true;String value = getServletConfig().getInitParameter("validating");if ("false".equalsIgnoreCase(value)|| "no".equalsIgnoreCase(value)|| "n".equalsIgnoreCase(value)|| "0".equalsIgnoreCase(value)) {validating = false;}return validating;}/** * 加载org.apache.struts.util.PropertyMessageResourcesFactory并实例化<br>* @throws ServletException*/protected void initInternal() throws ServletException {try {internal = MessageResources.getMessageResources(internalName);} catch (MissingResourceException e) {throw new UnavailableException("Cannot load internal resources from '" + internalName + "'");}}/** * 从web.xml中获得struts配置文件<br>* convertNull - 如果这个参数的值为 true, 数值型Java 包装类(比如java.lang.Integer)的初始值将会是null,而不是0。缺省值[false]<br>* @throws ServletException*/protected void initOther() throws ServletException {String value = null;value = getServletConfig().getInitParameter("config");if (value != null) {config = value;}value = getServletConfig().getInitParameter("convertNull");if ("true".equalsIgnoreCase(value)|| "yes".equalsIgnoreCase(value)|| "on".equalsIgnoreCase(value)|| "y".equalsIgnoreCase(value)|| "1".equalsIgnoreCase(value)) {convertNull = true;}if (convertNull) {ConvertUtils.deregister();ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);ConvertUtils.register(new BooleanConverter(null), Boolean.class);ConvertUtils.register(new ByteConverter(null), Byte.class);ConvertUtils.register(new CharacterConverter(null), Character.class);ConvertUtils.register(new DoubleConverter(null), Double.class);ConvertUtils.register(new FloatConverter(null), Float.class);ConvertUtils.register(new IntegerConverter(null), Integer.class);ConvertUtils.register(new LongConverter(null), Long.class);ConvertUtils.register(new ShortConverter(null), Short.class);}}/** * Digester组件用于XML文档到JAVA对象的映射处理<br>* @throws ServletException*/protected void initServlet() throws ServletException {this.servletName = getServletConfig().getServletName();Digester digester = new Digester();digester.push(this);digester.setNamespaceAware(true);digester.setValidating(false);for (int i = 0; i < registrations.length; i += 2) {URL url = this.getClass().getResource(registrations[i + 1]);if (url != null) {digester.register(registrations[i], url.toString());}}digester.addCallMethod("web-app/servlet-mapping", "addServletMapping", 2);digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);if (log.isDebugEnabled()) {log.debug("Scanning web.xml for controller servlet mapping");}InputStream input = getServletContext().getResourceAsStream("/WEB-INF/web.xml");if (input == null) {log.error(internal.getMessage("configWebXml"));throw new ServletException(internal.getMessage("configWebXml"));}try {digester.parse(input);} catch (IOException e) {log.error(internal.getMessage("configWebXml"), e);throw new ServletException(e);} catch (SAXException e) {log.error(internal.getMessage("configWebXml"), e);throw new ServletException(e);} finally {try {input.close();} catch (IOException e) {log.error(internal.getMessage("configWebXml"), e);throw new ServletException(e);}}if (log.isDebugEnabled()) {log.debug("Mapping for servlet '" + servletName + "' = '" + servletMapping + "'");}if (servletMapping != null) {getServletContext().setAttribute(Globals.SERVLET_KEY, servletMapping);}}protected void process(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {ModuleUtils.getInstance().selectModule(request, getServletContext());ModuleConfig config = getModuleConfig(request);RequestProcessor processor = getProcessorForModule(config);if (processor == null) {processor = getRequestProcessor(config);}processor.process(request, response);}}


阅读全文(3517) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.047 second(s), page refreshed 144780913 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号