Example tutorials used by interceptors in the Java STRUTS2 Framework _java

Source: Internet
Author: User
Tags file upload i18n prepare stub

1, Interceptor Small medium

The Interceptor function is similar to the filter in the Web.xml file, can intercept the user's request, and control the page by intercepting the user's request. Interceptors are configured in Struts-core-2.2.3.jar, and the original interceptors are configured in Struts-default.xml, which holds the basic use of interceptors.
The Struts2 interceptor function is similar to a servlet filter. Before the action executes the Execute method, STRUTS2 first executes the interceptor referenced in Struts.xml, and if multiple interceptors are executed sequentially in the order of the upper and lower orders, the Execute method of the action is executed after all the Interceptor's interceptor methods have been executed.
The STRUTS2 interceptor must implement the interface from the Com.opensymphoy.xwork2.interceptor.Interceptor, and in the defined interceptor there are three methods that need to be implemented:

void Destroy ();  
void Init ();  
String Intercept (actioninvocation invocation) throws Exception; 

The custom interceptor needs to rewrite the top three methods. In addition Struts2 's interceptor configuration file Struts.xml It is inherited from the original file Struts-default.xml file, so that in the corresponding <package> All of the configuration information in the Struts-default.xml is automatically owned. The specific code is as follows:

 
 

2. Add Interceptor

To use interceptors must be configured, STRUTS2 is a mapping method, so you want to use a function must be configured in the configuration file, interceptors are no exception. Therefore, the corresponding interceptor element must be added to the package, and the interceptor is associated with the corresponding class file, so that the appropriate interceptor is executed before the action is executed, and the following methods are used.

(1) Add a profile struts.xml and add interceptors to the file

<package name= "Testlogin" namespace= "/" extends= "Struts-default" > 
  <!--interceptor--> 
  <interceptors > 
    <interceptor name= "Myinterceptor" class= "Com.interceptor.MyInterceptor" ></interceptor> 
  </interceptors> 
     
  <action name= "demo" class= "Com.action.LoginAction" > 
    <result name= "Error" Type= "redirect" >/error.jsp</result> 
    <result name= "Success" >/success.jsp</result> 
    <result name= "CheckError" >/checkSession.jsp</result> 
    <interceptor-ref name= "Myinterceptor" ></interceptor-ref> 
    <interceptor-ref name= "Defaultstack" ></interceptor-ref> 
  < /action> 
</package> 

An interceptor named Myinterceptor is added to the above package, and a Java class is registered for the interceptor, the class name is Myinterceptor, and is sealed in the Com.interceptor package. In addition, the appropriate action is added to the package, and the Myinterceptor interceptor is executed first before executing the action.

(2) write the registered interceptor class Myinterceptor, the class must implement the Com.opensymphoy.xwork2.interceptor.Interceptor interface and rewrite the corresponding method

Package com.interceptor; 
 
Import Java.util.Map; 
Import Com.entity.User; 
Import Com.opensymphony.xwork2.ActionContext; 
Import com.opensymphony.xwork2.ActionInvocation; 
 
Import Com.opensymphony.xwork2.interceptor.Interceptor; 
   
   
  public class Myinterceptor implements interceptor{private user user; 
  Public user GetUser () {return user; 
  public void SetUser (user user) {this.user = user; @Override public void Destroy () {//TODO auto-generated Method Stub System.out.println ("----Destroy () 
  ----"); @Override public void init () {//TODO auto-generated Method stub System.out.println (-----init ()----- 
  --"); @Override public String Intercept (actioninvocation invocation) throws Exception {//TODO auto-generated Me 
    Thod stub System.out.println ("----intercept ()------"); 
    Map&lt;string, object&gt; session= invocation.getinvocationcontext (). GetSession (); if (Session.get ("username")!=null) {System.out.println ("Landing success!")     
      "); 
      Session.put ("username", user.getusername ()); 
    return Invocation.invoke (); }else{System.out.println ("Landing failed!") 
      "); 
    return "CheckError"; 

 } 
  } 
 
}

(3) After the first two steps, the interceptor has been configured to complete, the last one is to use the interceptor, the display page to add the appropriate label, and for the label specified above created by the name of the demo action, and then execute the page can be printed in the console the corresponding interceptor content.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 " 
  pageencoding=" UTF-8 "%> 
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 
 
 

Print output:

Analysis output, the program compilation phase will first read the configuration file Struts.xml, in the profile action in order to find whether the interceptor added, if the interceptor is added according to the interceptor name in <interceptors> To find out whether the interceptor or interceptor stack is defined in the if it is found that the interceptor is defined according to the interceptor to find the corresponding registered class, and finally find the registered class in the package and execute the corresponding init () method, the general process of the program run phase and compile phase similar, after the user submitted the request in the foreground, will be in accordance with the registered action in the Struts.xml to find the corresponding, if the search will find the interceptor, did not find the words will be the corresponding error, and finally execute the Interceptor registration class intercept method.

3, Interceptor Stack

Interceptor also has the concept of stack, it is the use of interceptors defined in a common state to achieve unified management, so that in the package can be used to share the interceptor, greatly facilitated the use of interceptors. In a package is often used to repeat the interceptor, if every time in the action to add interceptor-ref will be very troublesome, then the interceptor stack is to solve this problem, the specific configuration is as follows:

 <package name= "Testlogin" namespace= "/" extends= "Struts-default" > <!--interceptors --> <interceptors> <interceptor name= "Myinterceptor" class= "Com.interceptor.MyInterceptor" ><  
        /interceptor> <!--defines a common interceptor chain, which only needs to refer to the Interceptor chain--> <interceptor-stack name= "Defaultstack1" in the action tag > <interceptor-ref name= "Myinterceptor" ></interceptor-ref> <interceptor-ref name= "DefaultS" Tack "></interceptor-ref> </interceptor-stack> </interceptors> <action name= 
      "Demo" class= "Com.action.LoginAction" > <result name= "error" type= "redirect" >/error.jsp</result> <result name= "Success" >/success.jsp</result> <result name= "CheckError" >/checksession.jsp</r esult> <interceptor-ref name= "Defaultstack1" ></interceptor-ref> </action> </PACKAGE&G 
T 

The example uses the Interceptor-stack to define an interceptor stack named Defaultstack1, adds the interceptor to execute in the stack, encapsulates the interceptor, calls the interceptor stack directly in the action, and realizes the sharing of the interceptor stack.

4, the default interceptor stack

Alternatively, you can define the default interceptor stack, which means that if an interceptor is not defined in an action, it will execute the public interceptor by default. It belongs to the same class as the interceptors label, using the DEFAULT-INTERCEPTOR-REF definition.

&lt;package name= "Testlogin" namespace= "/" extends= "Struts-default" &gt; &lt;!--Interceptor--&gt; &lt;interceptors&gt; &lt;interceptor name= "Myinterceptor" class= "Com.interceptor.MyInterceptor" &gt;&lt;/interceptor&gt; &lt;!--define public interception Chain, the action tag only needs to reference the interceptor chain--&gt; &lt;interceptor-stack name= "Defaultinter" &gt; &lt;interceptor-ref name= "Myinterc" Eptor "&gt;&lt;/interceptor-ref&gt; &lt;interceptor-ref name=" Defaultstack "&gt;&lt;/interceptor-ref&gt; &lt;/in Terceptor-stack&gt; &lt;/interceptors&gt; &lt;!--define the default interceptor stack, which is automatically registered in the action--&gt; &lt;default-interceptor-ref 
    Name= "Defaultinter" &gt;&lt;/default-interceptor-ref&gt; &lt;action name= "demo" class= "Com.action.LoginAction" &gt; &lt;result name= "error" type= "redirect" &gt;/error.jsp&lt;/result&gt; &lt;result name= "Success" &GT;/SUCCESS.JSP&L 

 t;/result&gt; &lt;result name= "checkerror" &gt;/checkSession.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt;

The default interceptor stack is defined to execute a custom default interceptor stack only if the action does not specify an interceptor, and if the interceptor is redefined in the action, it overrides the custom default interceptor stack.

5. Do not execute any interceptor

There is also a situation where a default interceptor is defined in a package, but no interceptor is required to execute in a given action, then a interceptor called Defaultstack can be added to the corresponding action, which is the system's default interceptor. There will be no action.

&lt;package name= "Testlogin" namespace= "/" extends= "Struts-default" &gt; &lt;!--Interceptor--&gt; &lt;interceptors&gt; &lt;interceptor name= "Myinterceptor" class= "Com.interceptor.MyInterceptor" &gt;&lt;/interceptor&gt; &lt;!--define public interception Chain, the action tag only needs to reference the interceptor chain--&gt; &lt;interceptor-stack name= "Defaultinter" &gt; &lt;interceptor-ref name= "Myinterc" Eptor "&gt;&lt;/interceptor-ref&gt; &lt;interceptor-ref name=" Defaultstack "&gt;&lt;/interceptor-ref&gt; &lt;/in Terceptor-stack&gt; &lt;/interceptors&gt; &lt;!--define the default interceptor stack, which is automatically registered in the action--&gt; &lt;default-interceptor-ref 
    Name= "Defaultinter" &gt;&lt;/default-interceptor-ref&gt; &lt;action name= "demo" class= "Com.action.LoginAction" &gt; &lt;result name= "error" type= "redirect" &gt;/error.jsp&lt;/result&gt; &lt;result name= "Success" &GT;/SUCCESS.JSP&L t;/result&gt; &lt;result name= "CheckError" &gt;/checkSession.jsp&lt;/result&gt; &lt;!--add Defaultstack guarantee does not execute Interceptor--&gt; &lt;intercEptor-ref name= "Defaultstack" &gt;&lt;/interceptor-ref&gt; &lt;/action&gt; &lt;/package&gt; 

 

6. Interception method

6.1 Usage
The interceptor above only implements the interception of the action, in fact the interceptor function is very powerful, it can intercept the corresponding action method. and intercept action is different is to intercept the method must inherit class Methodfilterinterceptor, the class is sealed in Xwork-core.jar, once again proved that WebWork is the core of Struts2. In addition, you need to add the appropriate properties to the configuration file to determine the method of blocking and not to intercept the method, the specific configuration method is as follows:

&lt;package name= "Testlogin" namespace= "/" extends= "Struts-default" &gt; &lt;!--Interceptor--&gt; &lt;interceptors&gt; &lt;interceptor name= "Myinterceptor" class= "Com.interceptor.MyInterceptor" &gt;&lt;/interceptor&gt; &lt;!--define public interception Chain, the action tag only needs to reference the interceptor chain--&gt; &lt;interceptor-stack name= "Defaultinter" &gt; &lt;interceptor-ref name= "Myinterc" Eptor "&gt;&lt;/interceptor-ref&gt; &lt;interceptor-ref name=" Defaultstack "&gt;&lt;/interceptor-ref&gt; &lt;/in terceptor-stack&gt; &lt;/interceptors&gt; &lt;action name= "demo" class= "Com.action.LoginAction" &gt; &lt;res Ult name= "error" type= "redirect" &gt;/error.jsp&lt;/result&gt; &lt;result name= "Success" &gt;/success.jsp&lt;/result &gt; &lt;result name= "checkerror" &gt;/checkSession.jsp&lt;/result&gt; &lt;!--Configure blocking methods in Defaultstack, parameters inclu Add the Blocked method name to the Demethods, excludemethods add the name that does not need to be intercepted--&gt; &lt;interceptor-ref name= "Defaultstack" &gt; &lt;param na Me= "Includemethods" &gt; Add to InterceptMethod name &lt;/param&gt;&lt;!--Intercept method--&gt; &lt;param name= "Excludemethods" &gt; Add a method name that does not need to be intercepted &lt;/param&gt;&lt;!--no interception Method- 

 -&gt; &lt;/interceptor-ref&gt; &lt;/action&gt; &lt;/package&gt;

Code in the class that inherits the corresponding blocking method of the Methodfilterinterceptor class:

Package com.interceptor; 
 
Import Java.util.Map; 
Import Com.opensymphony.xwork2.ActionContext; 
Import com.opensymphony.xwork2.ActionInvocation; 
Import Com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; 
 
public class Inter extends Methodfilterinterceptor { 
 
  @Override public 
  String dointercept (actioninvocation Invocation) throws Exception { 
    System.out.println ("--intercept ()-"); 
    Gets the corresponding session 
    map<string,object> Session=invocation.getinvocationcontext (). getsession (); 
     
    Map request= (map) Actioncontext.getcontext (). Get ("request"); 
     
    String Username= (String) request.get ("User.username"); 
    if (Session.get ("username")!= null) { 
      String result=invocation.invoke (); 
       
      System.out.println ("--end ()-"); 
      return result 
    }} 
  } 
 
 

The

6.2 Demo
looks at an instance of an interception method and analyzes the results. The following example shows the output of the blocking method, creates a Loginaction class in the instance, and adds the method to be executed by the action; Inter class, the Interceptor overrides the Methodfilterinterceptor method, Whether a method is blocked by output in the console, login.jsp file, add three buttons, and demonstrate the execution of three methods respectively.
(1) The definition of a Struts.xml method interceptor, in which a package named Inter is defined, and parameters are specified in the Interceptor, Includemethods used to intercept method1,excludemethods in METHOD2 representations not to intercept m Ethods2 method, configure the following code:

&lt;! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.0//en" "Http://struts.apache. Org/dtds/struts-2.0.dtd "&gt; &lt;struts&gt; &lt;constant name=" struts.action.extension "value=", "&gt;&lt;/constant &gt; &lt;package name= "Login" extends= "Struts-default" &gt; &lt;interceptors&gt; &lt;interceptor name= " Inter "class=" Com.interceptor.inter "&gt; &lt;param name=" includemethods "&gt;Method1&lt;/param&gt; &lt;!--intercept Metho D1 method--&gt; &lt;param name= "Excludemethods" &gt;Method2&lt;/param&gt; &lt;/interceptor&gt; &lt;inter Ceptor-stack name= "Myinterceptor" &gt; &lt;interceptor-ref name= "Inter" &gt;&lt;/interceptor-ref&gt; &lt;i Nterceptor-ref name= "Defaultstack" &gt;&lt;/interceptor-ref&gt; &lt;/interceptor-stack&gt; &lt;/interceptors&gt 
       
    ; &lt;action name= "loginaction" class= "com.action.loginAction" &gt; &lt;result name= "Success" &gt;success.jsp&lt;/resu 
Lt&gt;      &lt;result name= "error" &gt;error.jsp&lt;/result&gt; &lt;result name= "Cancel" type= "Redirectaction" &gt;welcome &lt;/result&gt; &lt;interceptor-ref name= "Inter" &gt;&lt;/interceptor-ref&gt; &lt;interceptor-ref name= "Defau" 

 Ltstack "&gt;&lt;/interceptor-ref&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt;

(2) Loginaction class, configure the action in login.jsp, add method1-method3 three methods in the class, where Method1 is intercepted, METHOD2 and Method3 are not intercepted, and finally we look at the output.

Package com.action; 
 
Import Com.opensymphony.xwork2.ActionSupport; public class Loginaction extends Actionsupport {@Override public String execute () throws Exception {if (this.u 
    Sername.equals ("admin") &amp;&amp; this.password.equals ("admin")) {return "success"; 
    }else if (This.username.equals ("Cancel") &amp;&amp; this.password.equals ("Cancel") {return "Cancel"); 
    }else{return "error"; 
  } public void Method1 () {System.out.println ("Execute Method: Method1"); 
  public void Method2 () {System.out.println ("execution method: Method2"); 
  public void Method3 () {System.out.println ("execution method: Method3"); 
  Private String username; 
   
  private String password; 
  Public String GetUserName () {return this.username; 
  public void Setusername (String username) {this.username=username; 
  Public String GetPassword () {return this.password; } public void SetPassword (String PassWord) {This.password=password; 

 } 
   
   
}

(3) Inter class, Inherit Methodfilterinterceptor class, use to implement interception method. Rewrite the Dointercept method to add appropriate information for the interception in the method.

Package com.interceptor; 
 
Import java.util.Date; 
Import Java.util.Map; 
 
Import com.action.loginAction; 
Import Com.opensymphony.xwork2.ActionContext; 
Import com.opensymphony.xwork2.ActionInvocation; 
Import Com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; 
 
public class Inter extends Methodfilterinterceptor { 
   
  @Override 
  protected String dointercept (actioninvocation Invocation) throws Exception { 
    //TODO auto-generated method stub  
     System.out.println ("Interceptor intercepts before action execution" +new Date ());  
     String Result=invocation.invoke (); Executes the action method 
     System.out.println ("Intercept the Interceptor after action execution" +new Date ());  
    return result;  
 
  } 
 
 

(4) login.jsp, add three buttons on the JSP page, and demonstrate three methods to judge the interception of the interceptor to the method. The three-button post-click action is dynamically added in JavaScript, which achieves a different action in a form, and of course there are other methods that will be discussed in the next post.

&lt;%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%&gt; &lt;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" &gt; &lt;html&gt; &L t;head&gt; &lt;meta http-equiv= "Content-type" content= "text/html"; Charset=utf-8 "&gt; &lt;title&gt;insert title here&lt;/title&gt; &lt;script type=" Text/javascript "&gt;//Method 1, definition blocked 
    The instance function method1 () {var form=document.forms[0] of the method; Form.action= "loginaction! 
    Method1 "; 
  Form.submit (); 
    }//Method 2, add a method that does not intercept for button 2 function method2 () {var form=document.forms[0]; Form.action= "loginaction! 
    Method2 "; 
  Form.submit (); 
    }//Method 3, add a method that does not intercept for button 3 function method3 () {var form=document.forms[0]; Form.action= "loginaction! 
    Method3 "; 
  Form.submit (); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; user name: &lt;input type= "text" name= "username" &GT;&LT;BR&G 
    T Password: &lt;input type= "text" name= "pasSword "&gt;&lt;br&gt; &lt;input type=" Submit "Name=" OK "value=" button 1 "onclick=" method1 () "&gt; &lt;input type=" submi T "name=" OK1 "value=" button 2 "onclick=" Method2 () "&gt; &lt;input type=" Submit "Name=" Ok2 "value=" button 3 "onclick=" Method3 () "& 
  Gt 

 &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;

After you run the completed Page view:

(5) Analysis of the results of the operation, respectively, click the button 1, 2, 3, in the console output results, Button 1 is bound method1, The method is intercepted in the struts.xml if the result is correct, the result of the interception is displayed, and the corresponding buttons 2 and 3 only output the running result because they are not intercepted. Then look at the following result chart:

The result graph is exactly the result of our analysis, where Button 1 was intercepted, the Dointercept method in the Inter class was executed, and the corresponding buttons 2 and 3 were not intercepted. That is, the Method1 is placed in the whitelist of the method interceptor, executed to intercept the method, and the METHOD2 is placed in the interceptor blacklist and does not need to intercept the method; Method3 does not do any processing.

7. Conclusion

As far as the contents of interceptors are summed up, interceptors provide powerful capabilities that allow developers to control the output at runtime and increase the flexibility of programming. In addition to any theoretical things do not try to remember, must be rational to analyze, a lot of practice, do a few examples, analysis results more profound understanding.

PS:STRUTS2 (xwork) provides a functional description of the Interceptor

Intercepting device

Name

Description

Alias Interceptor

Alias

Request parameters are converted between different requests in different name parts, and the request content is unchanged

Chaining Interceptor

Chain

let the previous one the properties of the action can be accessed by the latter action , now and chain type of result(<result type= "Chain" > ) used in combination.

Checkbox Interceptor

CheckBox

added a the checkbox automatically handles the code and sets the contents of the Unchecked checkbox to False, and the HTML does not commit the unchecked CheckBox.

Cookies Interceptor

Cookies

using the configured name,value refers to cookies.

Conversion Error Interceptor

Conversionerror

the error from Add to Action in actioncontext property field.

Create Session Interceptor

CreateSession

Automatic Creation HttpSession, used to HttpSession for needs Interceptor Service.

Debugging Interceptor

Debugging

Provide different debugging pages to show the internal data situation.

Execute and Wait Interceptor

Execandwait

performing in the background Action , while bringing the user to a waiting page in the middle.

Exception Interceptor

exception

To position an exception to a screen

File Upload Interceptor

FileUpload

Provide file Upload function

I18N Interceptor

i18n

Record User-selected locale

Logger Interceptor

Logger

Output Action 's name

Message Store Interceptor

Store

storage or Access implementation Action for Validationaware interface the class appears with a message, Error, field error, and so on.

Model Driven Interceptor

Model-driven

if a class implements the Modeldriven, the result of Getmodel is placed in Value Stack in.

Scoped Model Driven

Scoped-model-driven

If a Action implements the Scopedmodeldriven, the Interceptor takes the model call Action from the corresponding Scope The Setmodel method puts it inside the Action .

Parameters Interceptor

Params

set the parameters in the request to Action in.

Prepare Interceptor

Prepare

if Acton implements the Preparable, the interceptor invokes the prepare of the Action class method.

Scope Interceptor

Scope

will be Action Status stored in session and application the simple method.

Servlet Config Interceptor

ServletConfig

Provide access httpservletrequest and httpservletresponse methods to Map Way to access.

Static Parameters Interceptor

Staticparams

from In the struts.xml file , set the contents of <param> in <action> to the corresponding action in.

Roles Interceptor

Roles

determines whether the user has The role specified by JAAS , otherwise it will not be executed.

Timer Interceptor

Timer

Output Action Time of execution

Token Interceptor

Token

through Token to avoid double-clicking

Token Session Interceptor

Tokensession

and Token Interceptor The same, but when you double-click the requested data stored in the session in

Validation Interceptor

Validation

Use Action-validation.xml The content that is defined in the file verifies the submitted data.

Workflow Interceptor

Workflow

Call Action Validate method, once returned with error, reposition to INPUT Screen

Parameter Filter Interceptor

N/A

Remove unnecessary parameters from the argument list

Profiling Interceptor

Profiling

Activate by parameter Profile

Related Article

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.