Struts2 knowledge points carding

1. Introduction to Struts2

  1. Concept: A lightweight MVC framework, which mainly solves the problem of request distribution, focusing on the control layer and the presentation layer. Low intrusiveness and low coupling with business code. Struts2 implements MVC and provides a series of APIs to simplify the business development process in a modal way.

  2. Compared with Servlet

    Advantages: business code decoupling, improving development efficiency

    Disadvantages: low execution efficiency, need to use reflection, parsing XML and other technical means, complex structure

  3. How different frameworks implement MVC

    Servlet:

    

    Spring:

    

    Struts2:

    

 

 

 

Second, the use of Struts2

   1. Use steps

    Import the Struts2 core jar package

    Configure the front controller filter in web.xml

copy code

<filter>
    <filter-name>Struts2</fileter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Struts2</filter-name>
    <url-pattern>/*</url-pattern>
<filter-mapping>

copy code

 

    Create struts.xml (the format can refer to the DTD file in the root path of the core package, struts-default.xml)

    Write Controller Action

      - the method is public

      - The return value is of type String (the return value matches the name attribute of struts.xml->action->result, that is, the corresponding result is found according to this return value)

      - the parameter list is empty

    Create JSP pages

    Configure struts.xml

copy code

<struts>
    <!--
        package: package, used to encapsulate Action
        name: package name, there can be multiple packages under the root element, and they cannot have the same name as each other
        extends: inheritance, used to specify the inherited package, which is equivalent to copying the configuration information under the inherited package to the current package
        namespace: namespace, used to specify the access path of Action, must start with "/" -->
    <package name="test01" namespace="/test01" extends="struts-default">
        <!--action: business controller, used to register business controller components
            name: action name, used to specify the access path of the Action
            class: business controller component, used to specify the class corresponding to the business controller
            method: method, used to specify the method to be called when accessing the current action
            *请求URL:http://ip:port/projectName/namespace/ActionName.action
        -->
        <action name="hello" class="test01.konrad.action.HelloAction" method="execute">
            <!--result: output component for forwarding, redirection, direct output
                name: name, there can be multiple results under one action, and they cannot have the same name as each other
                The default value is forwarded, and the page to be forwarded is set in the element
            -->
            <result name="success">
                /hello.jsp
            </result>
        </action>
    </package>
</struts>

copy code

 

 

 

3. Parameter passing

  1.Action takes the value from the page  

    a) Basic property injection (Page, Action)

    

    b) Domain Model Injection (Page, Action)

    

  2. The page takes the value from the Action

    a) use EL expressions

     

    b) OGNL

 

4. OGNL

   1. Concept: Object Graph Navigation Language, is a powerful expression language, similar to EL. By default, Strut2 uses OGNL expressions to access Action data, and actually accesses Action through the ValueStack object.

  2. Usage: In Struts2, OGNL expressions should be combined with Struts2 tags to access data

    EL:${user.userName} <==> OGNL:<s:property value="user.userName">

    *a) Access basic properties <s:property value="property name"/>

    *b) Accessing entity objects <s:property value="object name.property name"/>

    c) access array/collection <s:property value="someArray[1]"/> | <s:property value="someList[1]"/>

    d)访问Map  <s:property value="someMap.key" />

    e)运算  <s:property value="'My name is' + name" />

    f) call method <s:property value="name.toUpperCase()" />

    g) Create collection <s:property value="{'a','b','c'}" /> ArrayList

    h)创建Map  <s:property value="#{'mm':'MM','nn':'NN'}" /> LinkedHashMap

      

5. ValueStack

  1. Concept: In Struts2, Action transmits data to the page, encapsulates the Action data, and allows JSP to access it through OGNL

  2. Principle

  

  3. Access ValueStack

    a) Observe its structure through <s:debug>

    b) Output the top of the stack: <s:property />

    c) Access the Context object:

      - OGNL expressions start with "#"

      - Use the key to access the value of the context object, that is, "#key" to get the value of an attribute in the context

    d) iterate over the collection  

     

    

    e) iterate by numbers

 

 

   4. Changes at the top of the ValueStack stack

    - By default the top of the stack is Action

    - During the loop process, the top of the stack is the loop variable (when the set is iterated, the loop variable is the object in the set, that is, the top of the stack is the entity object, and the OGNL expression can be written with the entity object as the root; when the number is iterated, the loop variable is the number , you cannot use numbers as entity objects, you need to declare the variable name through var and refer to it with "#variable name", in this case, the value is taken from the context object)

    - After the loop ends, the top of the stack changes back to Action

 

  5. EL expressions access ValueStack

    a) EL is also the value taken from ValueStack

    b) The default value range of EL is page, request, session, application

    c) The getAttribute method of the request rewritten by Struts2, first tries to get the value from the original request, if not, then gets the value from the ValueStack

 

6. Basic Principles of Action

   1.6 major core components

  

  FC: Front-end controller, responsible for uniform distribution of requests

  Action: business controller, responsible for handling a certain type of business

  ValueStack: The medium between Action and JSP data interaction

  Interceptor: Interceptor, responsible for extending Action and handling common affairs of Action

  Result: The component responsible for the output

  Tags: tags, responsible for displaying data and generating frames

  

  2. How to get Session

    a)ActionContext

      - ActionContext.getContext().getSesion(),返回Map<String, Object>

    b)ServletActionContext

      - ServletActionContext.getRequest().getSession(),返回HttpSession

    c) SessionAware (recommended)

      - Let Action implement the SessionAware interface

      - Implement the setSession(Map<String, Object> session) method, Struts2 will call the method after the Action is instantiated, and inject the Session object through the method parameters

      - Define member variables to receive the injected Session object

 

Seven, Result principle

   1. Introduction: A component used for output, which is used to output some content to the page. Forwarding and redirection can be understood as output in a special way. Each Result is actually a class, and these classes implement the common interface Result. Struts2 presets 10 types of Result, which are defined in strtus-default.xml

  2. Result type

    a) dispatcher: the result used for forwarding, which can forward the request to JSP. The class corresponding to this type of Result is ServletDispacherResult, and the Result is specified as the default Result type of Struts2 by default="true".

    b) stream: used to output binary data to the page, this type of Result can output binary data to the request initiator, the corresponding class is StreamResult

<result name="success" type="stream">
  <!--codeStream is the input stream InputStream defined in Action -->
    <param name="inputName">codeStream</param>
</result>

 

    c) redirectAction: used to redirect the request to another Action, the corresponding class is ServletActionRedirectResult

copy code

<result name="login" type="redirectAction">
    <!--If the redirected Action is under the same namespace as the current Action, you can omit the namespace-->
    <param name="namespace">
    /Namespaces
    </param>
    <param name="actionName">
    action name
    </param>
</result>

copy code

 

    d) json: It is used to output data in json format to the page, and the json string can be output to the request initiator. The corresponding class is JSONResult

copy code

<result name="success" type="json">
    <!--Output an Action property
    If the specified property is a basic type, the property value will be returned directly
    If the specified property is an entity object, the return format is {"code":"as1","name":"hk"}
    -->
    <param name="root">Attribute name</param>
    <!--Output multiple Action attributes-->
    <param name="includeProperties">property name 1, property name 2...</param>
    <!--Output all attributes, no param tag needed-->
   
</result>

copy code

 

    json needs to import packages, modify the package inheritance relationship to json-default

Eight, UI label

  1.表单  <s:form action="" method="" theme="simple" ></s:form>

  2. Text field <s:textfield name="userName" />

  3.布尔框  <s:checkbox name="marry" />

  4. Radio box <s:radio name="sex" list="#{'M':'Male','F':'Female'}"/> static initialization

        <s:radio name="favoriteCities" list="cities" listKey="cityCode" listValue="cityName" /> 动态初始化

  5. Multi-select box <s:checkboxlist name="travelCities" list="#{'01':'Beijing','02':'Shanghai','03':'Guangzhou'}" /> static initialization

        <s:checkboxlist name="travelCities" list="cities" listKey="cityCode" listValue="cityName" /> 动态初始化

  6. Drop-down selection <s:select name="home" list="#{'01':'Beijing','02':'Shanghai','03':'Guangzhou'}" /> static initialization

        <s:select name="home" list="cities" listKey="cityCode" listValue="cityName" /> 动态初始化

 

 

9. Interceptor

  1. Purpose: The interceptor is suitable for encapsulating some general processing for easy reuse. For example, request parameters are passed to Action attributes, log records, permission checks, transaction processing, etc. The interceptor is called by configuration, so the usage method is more flexible and easy to maintain and expand.

  2. Use steps

    Create an interceptor component (create a class, implement the Interceptor interface, and implement the intercept method; you can also inherit MethodFilterInterceptor, which can prevent a method in the action from being intercepted)

public String intercept(ActionInvocation invocation){
   //Interceptor--front part processing
   invocation.invoke();
   //Interceptor -- subsequent processing      
}

 

 

 

    register interceptor

<package>
    <interceptors>
        <interceptor name="alias" class="implementation class"/>
        <!--Other Interceptors-->
    </interceptors>
</package>

 

 

 

    Reference interceptor (which Action you want to be extended by the interceptor, you need to refer to the interceptor under this action configuration)

copy code

<action>
   <!--Manually use the system default interceptor once -->
   <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="Interceptor alias"/>
    <!--Can write multiple -->
   <!--You can use the excludeMethods parameter attribute to set methods that are not filtered-->
</action>

copy code

 

 

 

  

  3. Interceptor stack

<interceptor-stack name="myStack">
    <interceptor-ref name="Interceptor Alias ​​1"/>
    <interceptor-ref name="Interceptor Alias ​​2"/>
</interceptor-stack>

 

 

 

 

 

  4. FileUpload interceptor

    a) Principle: First, the FileUpload interceptor saves the file submitted in the form to the temporary path of the server in the form of a temporary file. After that, the FileUpload interceptor injects the temporary file object into the Action, and the Action handles the temporary file autonomously. Finally the FileUpload interceptor deletes the temporary file.

    b) use steps

      Guide package commons-io.jar

      Action: Define a File type attribute (such as some) to accept the temporary file object injected by the interceptor. If you want to get the original file name, you need to define a String type attribute, the attribute name is File type attribute + FileName (such as someFileName)

      Form settings: method="post", enctype="multipart/form-data"

    c) Set the limit (the default maximum value for Struts2 file upload is 2097152B, which is 2M)

      Reset default limit value in struts.xml <constant name="struts.multipart.maxSize" value="5000000" />

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325017688&siteId=291194637