Struts2 Finishing-----Struts2 Interceptor

Source: Internet
Author: User

The Struts2 interceptor is the core of the struts2, and its underlying implementation uses the Java reflection mechanism and dynamic proxy.

How to implement the Struts2 interceptor

1. Implement the Interceptor interface to implement the Init (), Destory (), intercept () method.

2. Inherit the Abstractinterceptor class, overriding the Intercept () method.

3. Inheriting the Methodfilterinterceptor class, overriding the Dointercept () method

Interceptor Implementation principle:

When the struts2 action is requested, STRUS2 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

Interceptor and filter comparison

1, interceptors are based on the reflection mechanism of Java, and filter is based on function callback

2. The filter relies on the servlet container, while the interceptor does not depend on the servlet container

3. Interceptors only work on action requests, while filters can work on almost all requests

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 called multiple times, and the filter can only be called once when the container is initialized

Create a new case

New Action
 Packagecom.aaron.action;ImportCom.opensymphony.xwork2.ActionContext;ImportCom.opensymphony.xwork2.ActionSupport; Public classUseractionextendsActionsupport {Private Static Final LongSerialversionuid = 1L; PrivateString name; //User Login     PublicString Login () {returnSUCCESS; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}
Write a filter
 Packagecom.aaron.action;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportOrg.apache.struts2.StrutsStatics;Importcom.opensymphony.xwork2.Action;ImportCom.opensymphony.xwork2.ActionContext;Importcom.opensymphony.xwork2.ActionInvocation;ImportCom.opensymphony.xwork2.interceptor.AbstractInterceptor; Public classAuthorityinterceptorextendsAbstractinterceptor {Private Static Final LongSerialversionuid = 1L; //Interception method for blocking action handling     PublicString Intercept (actioninvocation invocation)throwsException {System.out.println ("Into the Interceptor" ""); Actioncontext AC=Invocation.getinvocationcontext (); //Struts2 Interceptor Interceptor GET requestHttpServletRequest request=(HttpServletRequest) ac.get (strutsstatics.http_request); //Remove the Session property named UserString name = Request.getparameter ("name"); Try{System.out.println ("The resulting user name is:" +name); }Catch(Exception ex) {System.out.println ("Exception:" +ex.tostring ()); }        //If the login is not logged in, or if the username used is not Aaron, return to login again        if(Name! =NULL&& name.equals ("Aaron") {request.getsession (). SetAttribute ("MSG", "Login Successful"); Request.getsession (). SetAttribute ("Name", name); returnInvocation.invoke (); }        //ctx.put ("msg", "No permissions, Login again");Request.getsession (). SetAttribute ("msg", "No permissions, Login again"); //return directly to the logical view of login        returnAction.login; }} 

This directly determines whether the user name meets the requirements.

Ps:struts2 Interceptor Interceptor Get request:httpservletrequest request = (httpservletrequest) ac.get (strutsstatics.http_ REQUEST);


Configuring the Struts.xml file

<?XML version= "1.0"?>            <!DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "http://struts.apache.org/d Tds/struts-2.0.dtd "><Struts>    <constantname= "Struts.i18n.reload"value= "false" />    <constantname= "Struts.devmode"value= "false" />    < Packagename= "Default"extends= "Struts-default"namespace="/">        <!--The user interceptor is defined under this element -        <Interceptors>            <!--A interceptor named Checkuserlogin is defined. -            <Interceptorname= "Checkuserlogin"class= "Com.aaron.action.AuthorityInterceptor" />            <Interceptor-stackname= "Checkuserlogin_stack">                <!--applying the default interceptor stack must have -                <Interceptor-refname= "Defaultstack" />                <!--apply a custom interceptor -                <Interceptor-refname= "Checkuserlogin" />            </Interceptor-stack>        </Interceptors>        <!--defining the default Interceptor -        <Default-interceptor-refname= "Checkuserlogin" />        <!--defining global processing results -        <Global-results>            <resultname= "Login">login.jsp</result>        </Global-results>        <Actionname= "Login"class= "Com.aaron.action.UserAction"Method= "Login">            <resultname= "Success">success.jsp</result>            <resultname= "Login">login.jsp</result>        </Action>    </ Package></Struts>
Test

In addition to the Aaron user name can be logged in, enter the other user name displayed is " no permissions, sign in again . "

Struts2 Finishing-----Struts2 Interceptor

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.