Struts 2 interceptor and struts interceptor

Source: Internet
Author: User

Struts 2 interceptor and struts interceptor
What is the Struts 2 interceptor?

   

When a user requests an Action class in the background, the interceptor sends the page (data) to the browser before the execution of the Excute () method of the Action and after the Result returns the magic board attempt) some common operations are required to intercept data in the interceptor!

In simple terms, it is to filter the request and response information. It can be seen as a filter in Java EE, however, you must note that the interceptor can only intercept Action-type requests. If you directly request static file interceptors such as jsp files and Css Styles, you cannot filter them!

Why use interceptor?
   

Any excellent MVC Framework provides some common operations, such as encapsulation of request data, type conversion, data validation, parsing of uploaded forms, and preventing multiple forms from being submitted. In the early MVC framework, all these general operations were written to the core controller, but not all the requests used needed the implementation of these operations, as a result, the framework has poor flexibility and low scalability.

Struts2 places its core functions in the interceptor instead of the core controller. It defines the work that most controllers need to do separately by functions, and each interceptor only performs one function, the interceptor that completes these functions can be freely selected and flexibly combined. You only need to add the functions in the configuration file, which improves the flexibility of the framework.

How interceptor works
   

The Struts2 interceptor executes the Action and Result execution. Its implementation principle is similar to that of Servlet Filter. It is executed in a chain and intercepts the actually executed method (execute. First, the interceptor that executes the Action configuration. After the Action and Result are executed, the interceptor executes at a time (opposite to the previous execution order). In this chained execution process, any interceptor can be directly returned to terminate the execution of the remaining interceptor, Action, and Result.

When the invoke () method of ActionInvocation is called, The first interceptor in the Action configuration is executed. After the interceptor makes corresponding processing, it will call the invoke () method of ActionInvocation here, the ActionInvocation object is responsible for tracking the status of the execution process and giving control to the appropriate interceptor. ActionInvocation transfers the control to the interceptor by calling the intercept () method of the interceptor. Therefore, the execution process of the interceptor can be seen as a recursive process. Later, the interceptor continues to execute until the last Interceptor. The invoke () method will execute the Action execut () method.

The execution process of the interceptor is described in a diagram first.

<! -- Interceptor stack (a stack of interceptors can be stored. You only need to call defaultStack to call all the interceptors in the stack) --> <interceptor-stack name = "defaultStack"> <interceptor-ref name = "exception"/> <! -- Used to capture exceptions, and map the exception to the custom error page according to the type --> <interceptor-ref name = "alias"/> <interceptor-ref name = "servletConfig"/> <! -- Inject various objects from the Servlet API into the Action --> <interceptor-ref name = "i18n"/> <interceptor-ref name = "prepare"/> <interceptor-ref name = "chain"/> <interceptor-ref name = "scopedModelDriven"/> <interceptor-ref name = "modelDriven"/> <interceptor-ref name = "fileUpload"/> <! -- Convert files and metadata from multiple requests to common request data, so that they can be set in the Action attribute of the Formation --> <interceptor-ref name = "checkbox"/> <interceptor-ref name = "datetime"/> <interceptor-ref name = "multiselect"/> <interceptor-ref name = "staticParams"/> <! -- Set the parameters set through the param sub-element of action in the configuration file to the corresponding Action attribute --> <interceptor-ref name = "actionMappingParams"/> <interceptor-ref name = "params"/> <! -- Set the data in the request to the attribute in Action --> <interceptor-ref name = "conversionError"/> <interceptor-ref name = "validation"> <! -- Used for data verification --> <param name = "excludeMethods"> input, back, cancel, browse </param> </interceptor-ref> <interceptor-ref name = "workflow"> <! -- Terminate the execution process when a data validation error occurs --> <param name = "excludeMethods"> input, back, cancel, browse </param> </interceptor-ref> <interceptor-ref name = "debugging"/> <interceptor-ref name = "deprecation"/> </interceptor-stack>

Custom interceptor
  

I have introduced so many principles. Now let's write an interceptor to try it out. The following describes the functions of this example. First, when a user accesses our website, the interceptor is used to determine whether the user has logged on. If the user has not logged on, the system will jump to the logon page to log on:

If you have logged on, You can directly jump to the welcome page ,:

  

The html and login verification code on the page is not displayed here. Let's take a look at the code about the Interceptor. First, we need to define an interceptor class (this class implements com. opensymphony. xwork2.interceptor. interceptor interface ). The Code is as follows:

Package cn. wz. logindemo;

Import java. util. Map;

Import com. opensymphony. xwork2.ActionContext;
Import com. opensymphony. xwork2.ActionInvocation;
Import com. opensymphony. xwork2.interceptor. Interceptor;

Public class Myinterceptor implements Interceptor {
/**
*
*/
Private static final long serialVersionUID = 1L;
/**
* Implements the intercept () method of the Interceptor interface, which intercepts the operation,
*/
Public String intercept (ActionInvocation invoc) throws Exception {
ActionContext context = invoc. getInvocationContext (); // gets the Action context object
Map <String, Object> map = context. getSession (); // get the set of Session objects through the Action context (the Session essentially encapsulates a map set and obtains the Session through the getSession () method in a decoupled manner)
Boolean falg = map. containsKey ("userName"); // checks whether the user has logged on
If (falg ){
// If you have logged on, transfer the control to another interceptor or Action.
Return invoc. invoke ();

}
// If there is no logon, the system will return "input" and no longer execute other interceptors or actions to directly jump to the logon page.
Return "input ";
}
/**
* Implements the destory () method of the Interceptor interface. This method is called only once when the Interceptor is destroyed.
*/
Public void destroy (){

}
/**
* Implement the init method of the Interceptor interface. This method is called only once when the Interceptor is initialized.
*/
Public void init (){

}


}

Configure the interceptor in the Struts. xml file as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.