. Java programmer from Stupid Bird to rookie (47) detailed Struts2 (ix) built-in interceptor and custom interceptor details (with source code) __java

Source: Internet
Author: User

This article comes from: Cao Shenhuan blog column. Reprint please indicate the source:http://blog.csdn.net/csh624366188

In the last blog, we saw the specific implementation of the interceptor principle, and looked at the source (Details Struts2 (eight) interceptor implementation principle and source analysis), this blog, I'm going to take you through the STRUTS2 built-in interceptors and how to customize our own interceptors to achieve the functionality we want to achieve

Four. STRUTS2 Built-in Interceptor

There are many interceptors built into the Struts2 that provide the core functionality and optional advanced features of many Struts2. These built-in interceptors are configured in Struts-default.xml. Only the interceptor can be configured to work and run properly. Struts 2 has provided you with a rich and versatile, full-featured interceptor implementation. You can view the configuration of the default interceptor and interceptor chains from the struts-default.xml inside the Struts2 jar package. Built-in interceptors are defined in the STRUTS2, but not all of them work. Because not all interceptors are added to the default interceptor stack, only interceptors that are added to the default interceptor stack work, and look at the interceptors that are added to the default interceptor stack:

Let's take a look at how to add other interceptors to our application, and we take the timer interceptor as an example, and the timer interceptor can count the time of the action execution. We can modify the default interceptor in the package, then replace the Defaultstack interceptor stack configured in Struts-default, causing Struts2 to not function properly, such as the inability to get the value of the form, and so on. So how to properly configure it. The Defaultstack interceptor stack can be added on the basis of adding a new interceptor, which guarantees the presence of the Defaultstack interceptor stack.

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

    <interceptors>

        <interceptor-stack name= "Myinterceptor" >  ①

            <interceptor-ref name= "Timer"/> <interceptor-ref name=  

            "Defaultstack"/ >  

        </interceptor-stack>

    </interceptors>

    <default-interceptor-ref name= " Myinterceptor "/> ② <action name=" useraction "class=" com.kay.action.UserAction "

        >

        < Result name= "Success" >suc.jsp</result>

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

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

    </action>

</package>


① adds a custom interceptor stack that contains the time interceptor and the Defaultstack interceptor stack.

② sets the default interceptor stack for the current package as a custom interceptor stack.

Modifying package's default interceptor will be applied in all of the action in the package, and if you only want to add an interceptor to one of the action, you can not modify the default interceptor stack and add only the corresponding action:

<interceptor-ref name= "Timer"/>

<interceptor-ref name= "Defaultstack"/>

Note that here must not forget to add <interceptor-ref name= "Defaultstack"/>, if forgotten, most of the STRUTS2 function can not be achieved

Five. Define your own interceptor.

Although Struts 2 provides us with such a rich interceptor implementation, in some cases it does not meet our requirements, such as: Access control, when the user accesses an action each time, we have to check whether the user has logged in, If we do not log in we will be intercepted before the action is executed, we need to customize the interceptor, and we'll look at how to implement the Custom interceptor.

1. Implement Interceptor Class

All struts 2 interceptors directly or indirectly implement Interface Com.opensymphony.xwork2.interceptor.Interceptor. This interface provides a three

A method:

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

2) void Destroy (); The method corresponds to the init () method. The system will recall the method before 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 interceptor classes, because this class provides an empty implementation of the Init () and Destroy () methods. So we just need to implement the Intercept method. Another way to implement interceptors is to inherit the Methodfilterinterceptor class, which enables you to implement a partial intercept, which means that you can specify which method to intercept an action, or which method to intercept.

2. Register a custom Interceptor

The custom interceptor class is implemented and now registers the interceptor in struts;

1. Registers the interceptor, registers the interceptor in the package in the Struts.xml

<interceptors>

       <!--name: Interceptor names, Class: Custom Interceptor Classes-->

       <interceptorname= "Interceptor name class=" Custom Interceptor class path "/>

 </interceptors>


2. Using interceptors, define the following code in the action that needs to use the custom interceptor

<action>      

   <interceptor-refname= "Interceptor name"/>

</action>



Note: Because many of the functions of the struts2 are based on interceptors, if you only use a custom interceptor here, you will lose many of the core features of struts2; so you need to define an interceptor stack (consisting of one or more interceptors)

3) Interceptor Stack

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

       <!--need to be aware that the system's default interceptor stack should be placed in front, adding custom interceptors;-->

          < Interceptor-ref name= "Defaultstate"/>

          <interceptor-ref name= "Name of Custom Interceptor"/>

 Interceptor-stack>



4 Using Stacks in action

<action>       

     <interceptor-refname= "stack name or interceptor name"/> ...

</action>



5 If you need all the action to use a custom interceptor at this point, define a default interceptor

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

Note: If another interceptor is used in one action, the default interceptor will fail, and other interceptors can be added to the action to ensure that the default interceptor is available and additional interceptors are required.

Below I will inherit the Methodfilterinterceptor class to implement a permission control interceptor, other pages are not shown, here, show the Interceptor class and Struts.xml configuration:

Interceptor Class Authorinterceptor:

Package com.bzu.intecepter;

Import Java.util.Map;

Import Javax.servlet.http.HttpServletRequest;

Import Org.apache.struts2.StrutsStatics;

Import Com.opensymphony.xwork2.ActionContext;

Import com.opensymphony.xwork2.ActionInvocation;


Import Com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; public class Authorinterceptor extends Methodfilterinterceptor {@Override protected String dointercept (actioninvocatio n invocation) throws Exception {//TODO auto-generated method Stub Actioncontext context = Invocation.getinvocationcont


Ext (); HttpRequest httpservletrequest request = (httpservletrequest) context. Get (Strutsstatics.http_ by Actioncontext)

REQUEST);

Servletactioncontext can also be used to obtain HttpRequest//HttpServletRequest request = Servletactioncontext.getrequest ();

Gets the absolute path string currenturl = Request.getrequesturi () of the root directory;

Intercept to the relative path of the access, you can use this and the permission table comparison to do the appropriate permissions control String TargetUrl = currenturl.substring (Currenturl.indexof ("/", 1),

Currenturl.length ()); System.ouT.println (Currenturl + "...) + TargetUrl" + "+";

Get the session information through Actioncontext, return the map session = Context.getsession () in map form;

Gets the username value inside the container, if there is a description that the user has logged in, let him perform the operation if he is not logged in and let him login string username = (string) session.get ("username");

System.out.println (username+ "username");

if (username!= null) {Invocation.invoke ();
return "Login";

 }
}


to take a look at the specific struts.xml configuration:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.0//en" "Http://struts.apache.or G/dtds/struts-2.0.dtd "> <struts> <constant name=" struts.i18n.encoding "value=" Utf-8 "/> <packa GE name= "struts2" extends= "Struts-default" > <interceptors> <!--Configure an interceptor to operate without login--> & Lt;interceptor name= "Logininterceptor" class= "Com.bzu.intecepter.AuthorInterceptor" > <param name= "Excludem" Ethods ">login</param> </interceptor> <!--re-encapsulate a default interceptor stack--> <interce Ptor-stack name= "Mydefaultstack" > <interceptor-ref name= "Logininterceptor"/> ; Interceptor-ref name= "Defaultstack"/> </interceptor-stack> </interceptors> <!-- Set the default interceptor stack for this package--> <default-interceptor-ref name= "Mydefaultstack"/> <global-results> <result name= "Login" >/login.jsp</result> </global-results> <action Name= "Loginaction" class= "com.bzu.action.LoginAction" method= "Login" > <result name= "Success" >success.jsp </result> <result name= "fail" >fail.jsp</result> <result name= "Input" >login.jsp</result   

 > </action> </package> </struts>


The above is a simple permission control code implementation. Specific source code download address: Click to download


Finally, let's take a look at the difference between interceptors and filters:
There are many similarities between interceptors and filters, but there is a fundamental difference between the two. The main differences are as follows:
1 The interceptor is based on the Java reflection mechanism, and the filter is based on the function callback.
2 The filter relies on the servlet container, and the interceptor does not depend on the servlet container
3 The Interceptor can only function on the action request, and the filter works on almost any request.
4 The Interceptor can access the action context, the object in the value stack, and the filter cannot
5 in the life cycle of the action, the interceptor can be invoked multiple times, and the filter can only be invoked once when the container is initialized.

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.