Reprint-STRUTS2 Interceptor Configuration

Source: Internet
Author: User
Tags i18n

Source: http://blog.csdn.net/axin66ok/article/details/7321430

Directory (?) [-]

    1. Understanding Interceptors
      1. 1 What is an interceptor?
      2. 2 How to implement the Interceptor
    2. Interceptor Configuration
    3. Using interceptors
    4. Custom Interceptors
      1. 1 Implementing the Interceptor class
      2. 2 Using custom Interceptors
    5. Custom Interceptor Sample
      1. 1 Problem description
      2. 2 Implementing the Rights control interceptor class
      3. 3 Configuring the Rights control Interceptor
      4. 4 Run debugging
1. Understanding Interceptor 1.1. What is an interceptor:

Interceptors, which are used in AOP (aspect-oriented programming) to intercept a method or field before it is accessed, and then add some action before or after it. Interception is an implementation strategy of AOP.

The Chinese document in WebWork is interpreted as--interceptors are objects that dynamically intercept action calls. It provides a mechanism to enable developers to define code that executes before and after an action executes, or to prevent it from executing before an action executes. It also provides a way to extract the reusable parts of an action.

When it comes to interceptors, there's one more word you should know-the interceptor chain (Interceptor Chain, called the Interceptor stack interceptor stack in struts 2). The Interceptor chain is a chain that binds the interceptor in a certain order. When accessing an intercepted method or field, interceptors in the interceptor chain are called in the order in which they were previously defined.

1.2. How to implement the Interceptor:

Most of the time, the Interceptor method is invoked in the form of proxies. The block implementation of Struts 2 is relatively straightforward. When the request arrives at the servletdispatcher of Struts 2, struts 2 looks for the configuration file, instantiates the relative interceptor object based on its configuration, and then strings it into a list, the last one to invoke the interceptor in the list. Such as:

2. Interceptor Configuration

Struts 2 has provided you with a wide range of fully functional interceptor implementations. You can view the configuration of the default interceptor and Interceptor chain in the struts-default.xml of the Struts2 jar package.

STRUTS2 (Xwork) provides an interceptor function description:

Interception device

Name

Description

Alias Interceptor

Alias

The request parameter is converted between different requests and the request content is unchanged.

Chaining Interceptor

Chain

The property of the previous action can be accessed by the latter action, and is now used in conjunction with the chain type of result (<result type= "Chain" >).

Checkbox Interceptor

CheckBox

Added a checkbox to automatically process the code, setting the contents of the unchecked checkbox to False, while HTML does not submit a checkbox that is not checked by default.

Cookies Interceptor

Cookies

Use the configured Name,value to refer to cookies

Conversion Error Interceptor

Conversionerror

Add the error from Actioncontext to the action's property field.

Create Session Interceptor

CreateSession

The httpsession is automatically created to serve interceptors that need to use the httpsession.

Debugging Interceptor

Debugging

Provide different debugging pages to show the internal data condition.

Execute and Wait Interceptor

Execandwait

Executes the action in the background and takes the user to an intermediate waiting page.

Exception Interceptor

exception

Position the exception to a screen

File Upload Interceptor

FileUpload

Provide file Upload function

I18N Interceptor

i18n

Record User-selected locale

Logger Interceptor

Logger

The name of the output action

Message Store Interceptor

Store

Stores or accesses the message, Error, field error, and so on of the action class that implements the Validationaware interface.

Model Driven Interceptor

Model-driven

If a class implements Modeldriven, the results of Getmodel are placed in the value stack.

Scoped Model Driven

Scoped-model-driven

If an action implements Scopedmodeldriven, the interceptor will remove the model from the corresponding scope by invoking the Setmodel method of the action to put it inside the action.

Parameters Interceptor

Params

Set the parameters in the request to the action.

Prepare Interceptor

Prepare

If Acton implements Preparable, the interceptor invokes the prepare method of the action class.

Scope Interceptor

Scope

A simple way to put the action state into session and application.

Servlet Config Interceptor

ServletConfig

Provides access to HttpServletRequest and HttpServletResponse methods, which are accessed in map mode.

Static Parameters Interceptor

Staticparams

From the Struts.xml file, set the contents of <param> in <action> to the corresponding action.

Roles Interceptor

Roles

Determines whether the user has a role specified by Jaas, otherwise it is not executed.

Timer Interceptor

Timer

Output the time the action was executed

Token Interceptor

Token

Use tokens to avoid double-clicking

Token Session Interceptor

Tokensession

Same as token interceptor, but when you double-click to store the requested data in session

Validation Interceptor

Validation

Verifies the submitted data using the content defined in the Action-validation.xml file.

Workflow Interceptor

Workflow

Call the action's Validate method, and once the error returns, relocate to the input screen

Parameter Filter Interceptor

N/A

Remove unnecessary parameters from the parameter list

Profiling Interceptor

Profiling

Activate profile by parameter

To define the interceptor in the Struts.xml file, the Interceptor stack:

<package name= "My" extends= "Struts-default" namespace= "/manage" >

<interceptors>

<!--defining Interceptors--

<interceptor name= "Interceptor name" class= "Interceptor implementation Class"/>

<!--defining Interceptor stacks--

<interceptor-stack name= "Interceptor stack name" >

<interceptor-ref name= "Interceptor One"/>

<interceptor-ref name= "Interceptor Two"/>

</interceptor-stack>

</interceptors>

......

</package>

3. Using interceptors

Once you have defined the interceptor and interceptor stack, you can use this interceptor or interceptor stack to intercept the action. The Interceptor's interception behavior will be executed before the action's Exceute method executes.

<action name= "useropt" class= "Org.qiujy.web.struts2.action.UserAction" >

<result name= "Success" >/success.jsp</result>

<result name= "Error" >/error.jsp</result>

<!--use interceptors, typically configured after result--

<!--referencing the system's default interceptor--

<interceptor-ref name= "Defaultstack"/>

<interceptor-ref name= "Interceptor name or Interceptor stack name"/>

</action>

It is important to note that if an interceptor is specified for the action, the default interceptor stack of the system will be out of effect. To continue using the default interceptor, the default interceptor is manually introduced in the configuration file above.

4. Custom Interceptors

As a framework, extensibility is essential. While Struts 2 provides us with such a rich interceptor implementation, this does not mean that we lose the ability to create custom interceptors, and on the contrary, it is quite easy to customize interceptors in Struts 2.

4.1. Implement the Interceptor class:

All Struts 2 interceptors implement interface Com.opensymphony.xwork2.interceptor.Interceptor directly or indirectly. The interface provides three methods:

1) void Init (); After the interceptor is initialized, the system backs up the method before the interceptor performs interception. For each interceptor, this method executes only once.

2) void Destroy (); The method corresponds to the init () method. The system will callback this method until the interceptor instance is destroyed.

3) String intercept (actioninvocation invocation) throws Exception; This method is the interception action that the user needs to implement. The method returns a string as a logical view.

In addition, inheriting class com.opensymphony.xwork2.interceptor.AbstractInterceptor is a simpler way to implement an interceptor class, because this class provides an empty implementation of the Init () and Destroy () methods. This way we only need to implement the Intercept method.

4.2. Use a custom interceptor:

Two steps:

L define interceptors by <interceptor ...> elements.

L use interceptors by <interceptor-ref ...> elements.

5. Custom Interceptor Example 5.1. Problem Description:

Use a custom interceptor to complete control of user permissions: When a viewer needs to request an action, the app needs to check if the browser is logged in and has sufficient permissions to perform the operation.

5.2. Implement the Rights control interceptor class:

Authorizationinterceptor.java

Package Org.qiujy.common;

import Java.util.Map;

import com.opensymphony.xwork2.Action;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**

* Permission Check Blocker

*

* @author qiujy

* @version 1.0

*/

Public class Authorizationinterceptor extends abstractinterceptor {

/*

* Interception method to intercept action handling

*

*/

Public String Intercept (actioninvocation invocation) throws Exception {

Map session = Invocation.getinvocationcontext (). GetSession ();

String userName = (string) session.get ("UserName");

if (null ! = userName && username.equals ("test")) {

System. out. println ("Interceptor: Legitimate User Login---");

return Invocation.invoke ();

} Else {

System. out. println ("Interceptor: User not logged in---");

return Action. LOGIN;

}

}

}

5.3. Configure the rights control interceptor:

Struts.xml:

<! DOCTYPE Struts Public

"-//apache software foundation//dtd Struts Configuration 2.0//en"

"Http://struts.apache.org/dtds/struts-2.0.dtd" >

<struts>

<package name= "My" extends= "Struts-default" >

<interceptors>

<!--define rights control interceptors--

<interceptor name= "authority" class= "Org.qiujy.common.AuthorizationInterceptor"/>

</interceptors>

<!--define global processing results-

<global-results>

<!--The result of logic named login, mapped to/login.jsp page--

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

</global-results>

<action name= "Listall" class= "org.qiujy.web.struts2.action.UserAction" method= "Listalluser" >

<result name= "Success" >/listall.jsp</result>

<!--using Interceptors--

<interceptor-ref name= "Defaultstack"/>

<interceptor-ref name= "authority"/>

</action>

<action name= "useropt" class= "Org.qiujy.web.struts2.action.UserAction" >

<result name= "Success" >/success.jsp</result>

</action>

</package>

</struts>

See the source code for other pages.

5.4. Run the debug:

In the browser address bar directly enter Http://localhost:8080/AuthorityInterceptorDemo/listall.action to access, this action is configured with a rights blocker, all are transferred to the login page.

After logging in:

Re-visit http://localhost:8080/AuthorityInterceptorDemo/listall.action this link:

If you want to simplify the configuration of the Struts.xml file and avoid repeatedly configuring the interceptor on each action, you can configure the interceptor as a default interceptor stack. As follows:

<! DOCTYPE Struts Public

"-//apache software foundation//dtd Struts Configuration 2.0//en"

"Http://struts.apache.org/dtds/struts-2.0.dtd" >

<struts>

<package name= "My" extends= "Struts-default" >

<interceptors>

<!--define rights control interceptors--

<interceptor name= "authority"

class= "Org.qiujy.common.AuthorizationInterceptor"/>

<!--define an interceptor stack with permission controls--

<interceptor-stack name= "Mydefault" >

<interceptor-ref name= "Defaultstack"/>

<interceptor-ref name= "authority"/>

</interceptor-stack>

</interceptors>

<!--define the default interceptor--

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

<!--define global processing results-

<global-results>

<!--The result of logic named login, mapped to/login.jsp page--

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

</global-results>

<action name= "Listall"

Class= "Org.qiujy.web.struts2.action.UserAction"

method= "Listalluser" >

<result name= "Success" >/listall.jsp</result>

</action>

</package>

<package name= "Font" extends= "Struts-default" >

<action name= "useropt" class= "Org.qiujy.web.struts2.action.UserAction" >

<result name= "Success" >/success.jsp</result>

</action>

</package>

</struts>

Once the default interceptor stack is defined under a package, all actions under that package will use this interceptor stack. For those that do not want to use the interceptor stack, you should place it under a different package.

Reprint-STRUTS2 Interceptor Configuration

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.