struts2处理请求的过程分析

和struts2启动一样,它也有一个入口,那就是org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter的doFilter方法。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  2.   
  3.         HttpServletRequest request = (HttpServletRequest) req;  
  4.         HttpServletResponse response = (HttpServletResponse) res;  
  5.   
  6.         try {  
  7.             prepare.setEncodingAndLocale(request, response);  
  8.             prepare.createActionContext(request, response);  
  9.             prepare.assignDispatcherToThread();  
  10.             if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {  
  11.                 chain.doFilter(request, response);  
  12.             } else {  
  13.                 request = prepare.wrapRequest(request);  
  14.                 ActionMapping mapping = prepare.findActionMapping(request, response, true);  
  15.                 if (mapping == null) {  
  16.                     boolean handled = execute.executeStaticResourceRequest(request, response);  
  17.                     if (!handled) {  
  18.                         chain.doFilter(request, response);  
  19.                     }  
  20.                 } else {  
  21.                     execute.executeAction(request, response, mapping);  
  22.                 }  
  23.             }  
  24.         } finally {  
  25.             prepare.cleanupRequest(request);  
  26.         }  
  27.     }  

这部分包括设置编码,创建actioncontext,并把这个Distance变量设置到此线程的本地副本instance中

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private static ThreadLocal<Dispatcher> instance = new ThreadLocal<Dispatcher>();  

接下来是获得actionmapping。这个actionmapping是根据我们的request的uri来和配置文件中的设置匹配,得到相应的action。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public ActionMapping findActionMapping(HttpServletRequest request, HttpServletResponse response, boolean forceLookup) {  
  2.         ActionMapping mapping = (ActionMapping) request.getAttribute(STRUTS_ACTION_MAPPING_KEY);  
  3.         if (mapping == null || forceLookup) {  
  4.             try {  
  5.                 mapping = dispatcher.getContainer().getInstance(ActionMapper.class).getMapping(request, dispatcher.getConfigurationManager());  
  6.                 if (mapping != null) {  
  7.                     request.setAttribute(STRUTS_ACTION_MAPPING_KEY, mapping);  
  8.                 }  
  9.             } catch (Exception ex) {  
  10.                 dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);  
  11.             }  
  12.         }  
  13.   
  14.         return mapping;  
  15.     }  


还记得dispatcher.getContainer().getInstance(ActionMapper.class)的原理吗?从我们上篇文章中,这个已经说过,在struts2的初始化中,container已经创建成功了,而且这个容器中有factories的这个map,每项都是一个name和type组成的Key和它对应的对象工厂的Value组成的。我们看看getMapping是怎么实现的。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public ActionMapping getMapping(HttpServletRequest request,  
  2.                                     ConfigurationManager configManager) {  
  3.         ActionMapping mapping = new ActionMapping();  
  4.         String uri = getUri(request);  
  5.   
  6.         int indexOfSemicolon = uri.indexOf(";");  
  7.         uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;  
  8.   
  9.         uri = dropExtension(uri, mapping);  
  10.         if (uri == null) {  
  11.             return null;  
  12.         }  
  13.   
  14.         parseNameAndNamespace(uri, mapping, configManager);  
  15.   
  16.         handleSpecialParameters(request, mapping);  
  17.   
  18.         if (mapping.getName() == null) {  
  19.             return null;  
  20.         }  
  21.   
  22.         parseActionName(mapping);  
  23.   
  24.         return mapping;  
  25.     }  
  26.   
  27.     protected ActionMapping parseActionName(ActionMapping mapping) {  
  28.         if (mapping.getName() == null) {  
  29.             return mapping;  
  30.         }  
  31.         if (allowDynamicMethodCalls) {  
  32.             // handle "name!method" convention.  
  33.             String name = mapping.getName();  
  34.             int exclamation = name.lastIndexOf("!");  
  35.             if (exclamation != -1) {  
  36.                 mapping.setName(name.substring(0, exclamation));  
  37.   
  38.                 mapping.setMethod(name.substring(exclamation + 1));  
  39.             }  
  40.         }  
  41.         return mapping;  
  42.     }  


 

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. protected void parseNameAndNamespace(String uri, ActionMapping mapping,  
  2.                                          ConfigurationManager configManager) {  
  3.         String namespace, name;  
  4.         int lastSlash = uri.lastIndexOf("/");  
  5.         if (lastSlash == -1) {  
  6.             namespace = "";  
  7.             name = uri;  
  8.         } else if (lastSlash == 0) {  
  9.             // ww-1046, assume it is the root namespace, it will fallback to  
  10.             // default  
  11.             // namespace anyway if not found in root namespace.  
  12.             namespace = "/";  
  13.             name = uri.substring(lastSlash + 1);  
  14.         } else if (alwaysSelectFullNamespace) {  
  15.             // Simply select the namespace as everything before the last slash  
  16.             namespace = uri.substring(0, lastSlash);  
  17.             name = uri.substring(lastSlash + 1);  
  18.         } else {  
  19.             // Try to find the namespace in those defined, defaulting to ""  
  20.             Configuration config = configManager.getConfiguration();  
  21.             String prefix = uri.substring(0, lastSlash);  
  22.             namespace = "";  
  23.             boolean rootAvailable = false;  
  24.             // Find the longest matching namespace, defaulting to the default  
  25.             for (Object cfg : config.getPackageConfigs().values()) {  
  26.                 String ns = ((PackageConfig) cfg).getNamespace();  
  27.                 if (ns != null && prefix.startsWith(ns) && (prefix.length() == ns.length() || prefix.charAt(ns.length()) == '/')) {  
  28.                     if (ns.length() > namespace.length()) {  
  29.                         namespace = ns;  
  30.                     }  
  31.                 }  
  32.                 if ("/".equals(ns)) {  
  33.                     rootAvailable = true;  
  34.                 }  
  35.             }  
  36.   
  37.             name = uri.substring(namespace.length() + 1);  
  38.   
  39.             // Still none found, use root namespace if found  
  40.             if (rootAvailable && "".equals(namespace)) {  
  41.                 namespace = "/";  
  42.             }  
  43.         }  
  44.   
  45.         if (!allowSlashesInActionNames && name != null) {  
  46.             int pos = name.lastIndexOf('/');  
  47.             if (pos > -1 && pos < name.length() - 1) {  
  48.                 name = name.substring(pos + 1);  
  49.             }  
  50.         }  
  51.   
  52.         mapping.setNamespace(namespace);  
  53.         mapping.setName(name);  
  54.     }  


这段代码应该很简单吧。无非就是解析request的uri,获得它的namespace,name,method等,设置到actionmapping中。当获得了actionmapping后,就开始真正处理请求了。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. execute.executeAction(request, response, mapping);  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException {  
  2.         dispatcher.serviceAction(request, response, servletContext, mapping);  
  3.     }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,  
  2.                               ActionMapping mapping) throws ServletException {  
  3.   
  4.         Map<String, Object> extraContext = createContextMap(request, response, mapping, context);  
  5.   
  6.         // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action  
  7.         ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);  
  8.         boolean nullStack = stack == null;  
  9.         if (nullStack) {  
  10.             ActionContext ctx = ActionContext.getContext();  
  11.             if (ctx != null) {  
  12.                 stack = ctx.getValueStack();  
  13.             }  
  14.         }  
  15.         if (stack != null) {  
  16.             extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));  
  17.         }  
  18.   
  19.         String timerKey = "Handling request from Dispatcher";  
  20.         try {  
  21.             UtilTimerStack.push(timerKey);  
  22.             String namespace = mapping.getNamespace();  
  23.             String name = mapping.getName();  
  24.             String method = mapping.getMethod();  
  25.   
  26.             Configuration config = configurationManager.getConfiguration();  
  27.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  28.                     namespace, name, method, extraContext, truefalse);  
  29.   
  30.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());  
  31.   
  32.             // if the ActionMapping says to go straight to a result, do it!  
  33.             if (mapping.getResult() != null) {  
  34.                 Result result = mapping.getResult();  
  35.                 result.execute(proxy.getInvocation());  
  36.             } else {  
  37.                 proxy.execute();  
  38.             }  
  39.   
  40.            //................  
  41.     }  

前面一段是处理actioncontext和valuestack的内容。在createContextMap中根据原生的request,response等进行封装封装成map类型,再调用一个createContextMap的一个重载方法,把这些原生request,session等和封装后的map类型的request,session等放入到一个大的map中。如果你要在action中获得这些对象,也是可以的。

比如:Map<String, String> request=(Map<String, String>) ActionContext.getContext().get("request");对于Map类型的request用的字符串是"request",如果你想获得原生request也是可以的,但是不是"request",而是StrutsStatics.HTTP_REQUEST:

httprequest=(HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);在map中就是以StrutsStatics.HTTP_REQUEST为键。

但是你可能会问:为什么session可以这样获得呢?Map<String, Object> session=ActionContext.getContext().getSession();而request却要通过get方法呢?

这是因为在ActionContext中并没有提供getRequest方法,也不知道为什么不提供,其实getSession()也是通过get方法实现的。

接下来是获得mapping的命名空间,action的名字,action的方法名。我们执行action,不就是要知道这些么。然后获得一个action的代理:ActionProxy proxy。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext) {  
  2.           
  3.         ActionInvocation inv = new DefaultActionInvocation(extraContext, true);  
  4.         container.inject(inv);  
  5.         return createActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);  
  6.     }  

创建actioninvocation。通过container的IOC机制进行注入。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public ActionProxy createActionProxy(ActionInvocation inv, String namespace, String actionName, String methodName, boolean executeResult, boolean cleanupContext) {  
  2.           
  3.         StrutsActionProxy proxy = new StrutsActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);  
  4.         container.inject(proxy);  
  5.         proxy.prepare();  
  6.         return proxy;  
  7.     }  

此时才创建action的代理对象,以后就通过该代理对象去执行。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. protected void prepare() {  
  2.         String profileKey = "create DefaultActionProxy: ";  
  3.         try {  
  4.             UtilTimerStack.push(profileKey);  
  5.             config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName);  
  6.   
  7.             //.........  
  8.   
  9.             resolveMethod();  
  10.   
  11.             if (!config.isAllowedMethod(method)) {  
  12.                 throw new ConfigurationException("Invalid method: " + method + " for action " + actionName);  
  13.             }  
  14.   
  15.             invocation.init(this);  
  16.   
  17.         }   
  18.     //.........  
  19.     }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public void init(ActionProxy proxy) {  
  2.         this.proxy = proxy;  
  3.         Map<String, Object> contextMap = createContextMap();  
  4.   
  5.         // Setting this so that other classes, like object factories, can use the ActionProxy and other  
  6.         // contextual information to operate  
  7.         ActionContext actionContext = ActionContext.getContext();  
  8.   
  9.         if (actionContext != null) {  
  10.             actionContext.setActionInvocation(this);  
  11.         }  
  12.   
  13.         createAction(contextMap);  
  14.   
  15.         if (pushAction) {  
  16.             stack.push(action);  
  17.             contextMap.put("action", action);  
  18.         }  
  19.   
  20.         invocationContext = new ActionContext(contextMap);  
  21.         invocationContext.setName(proxy.getActionName());  
  22.   
  23.         // get a new List so we don't get problems with the iterator if someone changes the list  
  24.         List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());  
  25.         interceptors = interceptorList.iterator();  
  26.     }  

前面也是对context进行一些设置等,我就不分析了。

这里对actioninvocation进行了初始化操作,我们通过actioninvocation以后要执行一系列的interceptor和真正的action,所以这些东西都要在初始化中。

再回到serviceAction。因为我们已经得到了actionmapping和actionproxy。接下来就可以去执行拦截器interceptor和action了。

他们的执行就是如果还有interceptor就执行下一个interceptor,如果没有就执行真正的action了,采用一种责任链模式,这部分很简单,我也不分析。当action执行完后,又依次返回各个interceptor,再经过web服务器的各个容器中的各个valve(比如StandardContext容器的StandardContextValve)。这样就完成了整个的处理过程了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值