Detailed explanation of the use of Struts2 interceptor

How to use struts2 interceptor, or custom interceptor. In particular, when using the interceptor, you must refer to the default stack defaultStack of the interceptor that comes with struts2 in the Action, as follows (here I refer to the checkbox interceptor that comes with struts2):
<interceptor-ref name ="checkbox">
  <param name="uncheckedValue">0</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/> (must be added, otherwise an error)


can also be changed to global Action settings The interceptors you need are as follows:

Define global configuration settings in struts.xml
  <package name="struts-shop" extends="struts-default">
    <interceptors>
      <interceptor-stack name="myStack">
        <interceptor -ref name="checkbox">
          <param name="uncheckedValue">0</param>
       </interceptor-ref>


   jsp</result> </action> </package> Your interceptor is now working! ! HOHO the following are references





















Struts2's own configuration and its interceptor configuration



Struts2 Interceptor [Interceptor]



The working principle of the interceptor is as shown above, and each Action request is wrapped in a series of interceptors. The interceptor can perform similar operations after the Action executes the line or can perform the recycling operation after the Action executes the line.



Each Action can either transfer the operation to the following interceptor, or the Action can directly exit the operation and return to the client's predetermined screen.



How to customize an interceptor?

Customizing an interceptor requires three steps:

1. Customize a class that implements the Interceptor interface (or inherits from AbstractInterceptor).

2 Register the interceptor defined in the previous step in strutx.xml.

3 Refer to the interceptor defined above in the Action to be used. For convenience, the interceptor can also be defined as the default interceptor, so that all Actions are intercepted by this interceptor without special declaration.



The Interceptor interface declares three methods:



public interface Interceptor extends Serializable {



    void destroy();



    void init();



    String intercept(ActionInvocation invocation) throws Exception;

}



The Init method is after the interceptor class is created and before the Action image is intercepted The call is equivalent to a post-constructor method. Using this method, you can do the necessary initial operations for the interceptor class.



The Destroy method is called before the interceptor is garbage collected to reclaim the resources initialized by the init method.



Intercept is the main interception method of the interceptor. If you need to call the subsequent Action or interceptor, you only need to call the invocation.invoke() method in this method. You can insert the action before and after the method is called. The interceptor needs to do Methods. If you don't need to call subsequent methods, just return an object of type String, such as Action.SUCCESS.

In addition, AbstractInterceptor provides a simple implementation of Interceptor, which is:

public abstract class AbstractInterceptor implements Interceptor {



     public void init() {

    } public void

   

    destroy() {

    }





    public abstract String intercept(ActionInvocation invocation) throws Exception

;

When you need to write the init and destroy methods, you only need to inherit from AbstractInterceptor and implement the intercept method.



We try to write an interceptor for Session filtering. The interceptor checks whether there is a specific attribute (LOGIN attribute) in the user's Session. If it does not exist, the subsequent operation is aborted and the LOGIN is located. Otherwise, the original operation is performed. The code is:

public class CheckLoginInterceptor extends AbstractInterceptor {

    public static final String LOGIN_KEY = "LOGIN";

    public static final String LOGIN_PAGE = "global.login";



    public String intercept(ActionInvocation actionInvocation) throws Exception {



        System.out.println("begin check login interceptor!");

        // 对LoginAction不做该项拦截

        Object action = actionInvocation.getAction();

        if (action instanceof LoginAction) {

            System.out.println("exit check login, because this is login action.");

            return actionInvocation.invoke();

        }



        // 确认Session中是否存在LOGIN

        Map session = actionInvocation.getInvocationContext().getSession();

        String login = (String) session.get(LOGIN_KEY);

        if (login != null && login.length() > 0) {

            // Follow up if it exists operate.

            System.out.println("already login!");

            return actionInvocation.invoke();

        } else {

            // Otherwise terminate subsequent operations and return LOGIN

            System.out.println("no login, forward login page!");

            return LOGIN_PAGE;

        }

    }

}



register interceptors

<interceptors>

            <interceptor

name="login"

class="com.jpleasure.teamware.util.

            <interceptor-stack name="teamwareStack">

                <interceptor-ref name="login"/>

                <interceptor-ref name="defaultStack"/>

            </interceptor-stack>

</interceptors>



Set the above interceptor as default Interceptor:

<default-interceptor-ref name="teamwareStack"/>

This will be intercepted by login before all subsequent Actions in the same package are executed.





Function description of the interceptor provided by Struts2 (XWork): Interceptor Name



Description Alias ​​Interceptor alias Converts request parameters to files with different names between different requests . Action access, now and result of type chain (<result type=”chain”> )In conjunction with. Checkbox Interceptor checkbox













Added checkbox automatic processing code, setting the content of unselected checkboxes to false, and html does not submit unselected checkboxes by default.

Cookies Interceptor
Cookies
use the configured name and value to refer to cookies

Conversion Error Interceptor
conversionError
adds the error from the ActionContext to the Action's property field.

Create Session Interceptor
createSession
automatically creates HttpSession to serve interceptors that need to use HttpSession.

Debugging Interceptor
debugging
provides different debugging pages to show the internal data status.

Execute and Wait Interceptor
execAndWait
executes the Action in the background while taking the user to an intermediate waiting page.

Exception Interceptor
exception
locates the exception to a screen

File Upload Interceptor
fileUpload
provides file upload function

I18n Interceptor
i18n
records the locale

Logger Interceptor
logger selected by the user and
outputs the name of the Action

Message Store Interceptor
store
stores or accesses messages, errors, field errors, etc. that appear in the Action class that implements the ValidationAware interface.

Model Driven Interceptor
model-driven
If a class implements ModelDriven, the result obtained by getModel is placed in the Value Stack.

Scoped Model Driven
scoped-model-driven
If an Action implements ScopedModelDriven, the interceptor will take out the model from the corresponding Scope and call the Action's setModel method to put it inside the Action.

Parameters Interceptor
params
sets the parameters in the request to the Action.

Prepare Interceptor
prepare
If the Acton implements Prepareable, the interceptor calls the prepare method of the Action class.

Scope Interceptor
scope
Simple way to store Action state in session and application.

Servlet Config Interceptor
servletConfig
provides methods to access HttpServletRequest and HttpServletResponse in the form of Map.

Static Parameters Interceptor
staticParams
sets the content of <param> in <action> to the corresponding Action from the struts.xml file.

Roles Interceptor
roles
determine whether the user has the role specified by JAAS, otherwise it will not be executed.

The Timer Interceptor
timer
outputs the time when the Action is executed. The

Token Interceptor
token
avoids double-clicking the

Token Session Interceptor through the Token.
The tokenSession
is the same as the Token Interceptor, but when double-clicking, the requested data is stored in the Session.

Validation Interceptor
validation
uses the actions defined in the action-validation.xml file. Content check submitted data.

The Workflow Interceptor
workflow
calls the validate method of the Action. Once an error returns, relocate to the INPUT screen

. Parameter Filter Interceptor
N/A
Delete unnecessary parameters from the parameter list

Profiling Interceptor
profiling Register and reference the Interceptor
through the parameter activation profile <package name=" default" extends="struts-default">    <interceptors>        <interceptor name="timer" class=".."/>        <interceptor name="logger" class=".."/>    </interceptors>    <action name ="login" class="tutorial.Login">         <interceptor-ref name="timer"/>         <interceptor-ref name="logger" />         <result name="input">login.jsp</result>         <result name="success"




























            type="redirect-action">/secure/home</result>

   </action>

</package>



can combine multiple interceptors together as a stack call, when an interceptor stack is attached to an Action , in order for Action to execute, each interceptor in the interceptor stack must be executed.

<package name="default" extends="struts-default">

   <interceptors>

        <interceptor name="timer" class=".."/>

        <interceptor name="logger" class=".."/>

        <interceptor -stack name="myStack">

           <interceptor-ref name="timer"/>

           <interceptor-ref name="logger"/>

        </interceptor-stack>

    </interceptors>



    <



         <result name="input">login.jsp</result>

         <result name="success"

             type="redirect-action">/secure/home</result>

    </action>

</package>



Intercept as described above In the default Struts2 application, several interceptor stacks are configured by convention. For details, see struts-default.xml

. One of the interceptor stacks is special, and it will be applied to each default Action.

<interceptor-stack name="defaultStack">

    <interceptor-ref name="exception"/>

    <interceptor-ref name="alias"/>

    <interceptor-ref name="servletConfig"/>

    <interceptor-ref name=" prepare"/>

    <interceptor-ref name="i18n"/>

    <interceptor-ref name="





    <interceptor-ref name="scopedModelDriven"/>

    <interceptor-ref name="modelDriven"/>

    <interceptor-ref name="fileUpload"/>

    <interceptor-ref name="checkbox"/>

    <interceptor-ref name="staticParams"/>

    <interceptor-ref name="params">

      <param name="excludeParams">dojo"..*</param>

    </interceptor-ref>

    <interceptor-ref name="conversionError"/>

    <interceptor-ref name="validation">

        <param name="excludeMethods">input,back,cancel,browse</param>

    </interceptor-ref>

    <interceptor-ref name="workflow">

        <param name="excludeMethods">input,back,cancel,browse</param>

    </interceptor-ref>

Each interceptor has two default parameters: excludeMethods - filter out methods that do not use the interceptor and includeMethods - methods that use the interceptor. A few points to note:







































1 Interceptors are executed in the order defined, for example:

<interceptor-stack name="xaStack">

<interceptor-ref name="thisWillRunFirstInterceptor"/>

<interceptor-ref name="thisWillRunNextInterceptor"/>

<interceptor-ref name="followedByThisInterceptor"/>

<interceptor-ref name="thisWillRunLastInterceptor"/>

</interceptor-stack>

的执行顺序为:

thisWillRunFirstInterceptor

thisWillRunNextInterceptor

    followedByThisInterceptor

      thisWillRunLastInterceptor

        MyAction1

        MyAction2 (chain)

        MyPreResultListener

        MyResult (result)

      thisWillRunLastInterceptor

    followedByThisInterceptor

thisWillRunNextInterceptor

thisWillRunFirstInterceptor



2 Use the default interceptor to configure the interceptor stack required by each Action, for example:

<action name="login" class="tutorial.Login">

     <interceptor-ref name="timer"/>

     <interceptor-ref name="logger"/>

     <interceptor-ref name="default-stack"/>



     <result name="input">login.jsp</result>

     <result type="redirect-action">/secure/home< /result>

</action>

can be defined as follows:

<interceptors>

     <interceptor-stack name="myStack">

        <interceptor-ref name="timer"/>

        <interceptor-ref name=" logger"/>

        <interceptor-ref name="default-stack"/>

     </interceptor-stack>

</interceptors>



<default-interceptor-ref name="myStack"/>



<action name="login" class="tutorial.Login">

       <result name="input">login.jsp</result>

       <result type="redirect- action">/secure/home</result>

</action>



3 How to access HttpServletRequest, HttpServletResponse or HttpSession

There are two ways to achieve the effect, use ActionContext:

Map attibutes = ActionContext.getContext().getSession();

or implement the corresponding The interface:

HttpSession SessionAware

HttpServletRequest ServletRequestAware

HttpServletResponse ServletResponseAware


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326943203&siteId=291194637