Core and working principle of struts2, working principle of struts2
Recently, java development requires relevant open-source frameworks.
Before learning about struts2, we must first understand the purpose of using struts2? What benefits does it bring to us?
Design Objectives
The first goal of Struts design is to apply the MVC pattern to web programming. Here, the benefits of the MVC mode are not mentioned.
Technical advantages
Struts2 has two technical advantages. First, all Struts2 applications are based on The client/server HTTP Exchange Protocol. The Java Servlet API reveals that Java Servlet is only a small subset of Java APIs, in this way, we can use a powerful Java language for programming in the business logic section.
The second is to provide a clear implementation of MVC, which contains many key components involved in processing the request, such as the interceptor, OGNL Expression Language, and stack.
Because struts2 has such a goal and has such advantages, this is the reason for us to learn struts2. Next, we will thoroughly analyze the working principles of struts.
Working Principle
The following figure describes how Suruts2 works. Next we will introduce the core content of each step in steps.
Public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException... {HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ServletContext servletContext = filterConfig. getServletContext (); // HttpServletRequest and HttpServletResponse are processed here. DispatcherUtils du = DispatcherUtils. getInstance (); du. prepare (request, response); // set locale, encoding, and special request parameters like this method name. try... {request = du. wrapRequest (request, servletContext); // wrap the request} catch (IOException e )... {String message = "cocould not wrap servlet request with MultipartRequestWrapper! "; LOG. error (message, e); throw new ServletException (message, e);} ActionMapperIF mapper = ActionMapperFactory. getMapper (); // obtain the ER er ActionMapping mapping = mapper of the action. getMapping (request); // obtain the mapping if (mapping = null) of the action )... {// there is no action in this request, shocould we look for a static resource? String resourcePath = RequestUtils. getServletPath (request); if ("". equals (resourcePath) & null! = Request. getPathInfo ())... {resourcePath = request. getPathInfo ();} if ("true ". equals (Configuration. get (WebWorkConstants. WEBWORK_SERVE_STATIC_CONTENT) & resourcePath. startsWith ("/webwork "))... {String name = resourcePath. substring ("/webwork ". length (); findStaticResource (name, response);} else... {// this is a normal request, let it pass through chain. doFilter (request, response);} // WW did Its job here return;} Object o = null; try... {// setupContainer (request); o = beforeActionInvocation (request, servletContext); // the most important method of the entire framework. The following analyzes du. serviceAction (request, response, servletContext, mapping);} finally... {afterActionInvocation (request, servletContext, o); ActionContext. setContext (null) ;}} du. serviceAction (request, response, servletContext, mapping); // This method queries whether ActionMapper needs to call Action to process this (request) request. If ActionMapper decides to call an Action, FilterDispatcher submits the request processing to ActionProxy public void serviceAction (HttpServletRequest request, HttpServletResponse response, String namespace, String actionName, map requestMap, Map parameterMap, Map sessionMap, Map applicationMap )... {HashMap extraContext = createContextMap (requestMap, parameterMap, sessionMap, applicationMap, request, response, get ServletConfig (); // instantiate the Map request and ask whether ActionMapper needs to call an Action to process the (request) request extraContext. put (SERVLET_DISPATCHER, this); OgnlValueStack stack = (OgnlValueStack) request. getAttribute (ServletActionContext. WEBWORK_VALUESTACK_KEY); if (stack! = Null )... {extraContext. put (ActionContext. VALUE_STACK, new OgnlValueStack (stack);} try... {ActionProxy proxy = ActionProxyFactory. getFactory (). createActionProxy (namespace, actionName, extraContext); // here, actionName is parsed by two getactionnames. FilterDispatcher processes the request to ActionProxy. below is the TODO of ServletDispatcher: request. setAttribute (ServletActionContext. WEBWORK_VALUESTACK_KEY, proxy. getInvocation (). getStac K (); proxy.exe cute (); // execute ActionProxy if (stack! = Null )... {request. setAttribute (ServletActionContext. WEBWORK_VALUESTACK_KEY, stack) ;}} catch (ConfigurationException e )... {log. error ("cocould not find action", e); sendError (request, response, HttpServletResponse. SC _NOT_FOUND, e);} catch (Exception e )... {log. error ("cocould not execute action", e); sendError (request, response, HttpServletResponse. SC _INTERNAL_SERVER_ERROR, e );}}
4. If the ActionMapper decides to call an Action, FilterDispatcher will hand over the request processing to the ActionProxy.
5. ActionProxy asks the framework configuration file through ConfigurationManager and finds the Action class to be called. Here, we generally read from the struts. xml configuration.
6. ActionProxy creates an ActionInvocation instance.
7. The ActionInvocation instance uses the naming mode for calling. Before and after the Action is called, the call of the relevant Interceptor (Intercepter) is involved.
Let's take a look at how ActionInvocation works:
ActionInvocation is the core of Action Scheduling in Xworks. The Interceptor scheduling is the responsibility of ActionInvocation. ActionInvocation is an interface, while DefaultActionInvocation is the default Implementation of ActionInvocation by Webwork.
The scheduling process of Interceptor is roughly as follows:
1. During ActionInvocation initialization, all interceptors related to the Action are loaded according to the configuration.
2. Execute Interceptor when calling Action implementation through ActionInvocation. invoke method.
Interceptor separates many functions from our actions, greatly reducing the code of our actions, and the independent behaviors have good reusability. Many functions of XWork and WebWork are implemented by Interceptor. You can assemble the Interceptor Used by the Action in the configuration file. It runs before and after the Action is executed in the specified order.
Here, we will briefly introduce Interceptor
In struts2 comes a lot of interceptor, In the struts2-core-2.1.6.jar under this package of struts-default.xml we can find:
<interceptors> <interceptor name="alias"class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/> <interceptor name="autowiring"class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/> <interceptor name="chain"class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/> <interceptor name="conversionError"class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/> <interceptor name="clearSession"class="org.apache.struts2.interceptor.ClearSessionInterceptor"/> <interceptor name="createSession"class="org.apache.struts2.interceptor.CreateSessionInterceptor"/> <interceptor name="debugging"class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor"/> <interceptor name="externalRef"class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/> <interceptor name="execAndWait"class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/> <interceptor name="exception"class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/> <interceptor name="fileUpload"class="org.apache.struts2.interceptor.FileUploadInterceptor"/> <interceptor name="i18n"class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/> <interceptor name="logger"class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/> <interceptor name="modelDriven"class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/> <interceptor name="scopedModelDriven"class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/> <interceptor name="params"class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/> <interceptor name="actionMappingParams"class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/> <interceptor name="prepare"class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/> <interceptor name="staticParams"class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/> <interceptor name="scope"class="org.apache.struts2.interceptor.ScopeInterceptor"/> <interceptor name="servletConfig"class="org.apache.struts2.interceptor.ServletConfigInterceptor"/> <interceptor name="sessionAutowiring"class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/> <interceptor name="timer"class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/> <interceptor name="token"class="org.apache.struts2.interceptor.TokenInterceptor"/> <interceptor name="tokenSession"class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/> <interceptor name="validation"class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/> <interceptor name="workflow"class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/> <interceptor name="store"class="org.apache.struts2.interceptor.MessageStoreInterceptor"/> <interceptor name="checkbox"class="org.apache.struts2.interceptor.CheckboxInterceptor"/> <interceptor name="profiling"class="org.apache.struts2.interceptor.ProfilingActivationInterceptor"/> <interceptor name="roles"class="org.apache.struts2.interceptor.RolesInterceptor"/> <interceptor name="jsonValidation"class="org.apache.struts2.interceptor.validation.JSONValidationInterceptor"/> <interceptorname="annotationWorkflow"class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
The built-in interceptor of sturts2 is relatively convenient to use. We only need to add <interceptor-ref name = "to the action tag of struts. xml"Logger"/> And struts. xml extension struts-default, you can use,
To customize the interceptor, you must first write an interceptor class:
package ceshi;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor; publicclassAuthorizationInterceptor extends AbstractInterceptor { @Override public Stringintercept(ActionInvocation ai)throws Exception { System.out.println("abc"); return ai.invoke(); } }
Configure in struts. xml
<!DOCTYPEstruts PUBLIC"-//Apache SoftwareFoundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="test"extends="struts-default"> <interceptors> <interceptor name="abc"class ="ceshi.AuthorizationInterceptor"/> </interceptors> <action name="TestLogger"class="vaannila.TestLoggerAction"> <interceptor-refname="abc"/> <result name="success">/success.jsp</result> </action> </package></struts>
8. Once the Action is executed, ActionInvocation is responsible for finding the corresponding return result based on the configuration in struts. xml. The returned result is usually (but not always, or another Action chain) a template of JSP or FreeMarker to be represented. You can use the tag inherited from the Struts2 framework in the Process of representation. ActionMapper needs to be involved in this process
All objects (actions, Results, Interceptors, etc.) in the above process are created through ObjectFactory.
Comparison between Struts2 and struts1
Compared with struts1, struts2 is much simpler and more powerful. We can look at the following aspects:
From the perspective of architecture:Struts2 uses a large number of interceptor requests to allow separation from the business logic controller and servlet-api to avoid intrusion. struts1.x obviously intrude the servlet-api in the action.
Thread security analysis:Struts2.x is thread-safe. Every object generates an instance to avoid thread security issues. struts1.x is a single thread in action.
Performance:The struts2.x test can be performed without the web Container, while struts1.x depends on servlet-api. The test depends on the web container.
Comparison of request parameter encapsulation:Struts2.x uses the ModelDriven mode, so that we can directly encapsulate the model object without inheriting any base class of struts2, avoiding intrusion.
Advantages of labels:The tag library can almost completely replace the JSTL tag library, and struts2.x supports powerful ognl expressions.
Of course, compared with struts1, struts2 facilitates file upload and data verification. I will not discuss it in detail here.
A relatively good framework can help us develop qualified products more efficiently and stably, but we do not need to rely on the framework. As long as we understand our ideas and design patterns, we can expand our functions on our own, otherwise, let others take the lead forever!