Introduction and configuration usage of interceptors in struts2

Source: Internet
Author: User

Interceptors are the core of the STRUTS2 framework, and many of Struts2 's features are built on interceptors, which are objects that dynamically intercept action calls and provide a mechanism for developers to execute the required code before and after an action. You can organize his execution before an action executes, and do some work after the action is executed. He also provides a way to extract the reusable parts of an action.

Interception DeviceAn STRUTS2 interceptor is an implementation that implements interception before or after accessing an action or one of its methods, fields, Struts2 interceptors are pluggable and is an implementation of AOP (AOP is OOP (object-oriented programming, for The development of software technology and design ideas to a certain stage, as well as a perfect and complementaryIn general, interceptors are invoked through proxies, when a request arrives at Struts2 's Servletdispatcher (the Web HTTP request Scheduler, all requests to the action are invoked through Servletdispatcher), Struts2 looks for the configuration file and instantiates the relative interceptor object based on the configuration file configuration, and forms a list. Each action request is wrapped inside a series of interceptors. Interceptors can be prepared before the action executes. You can also do this later, with each action transferring the action to the following interceptor, or you can exit the operation directly. Interceptor ConfigurationWith the introduction of interceptors in Web applications, pluggable management of action-generic operations can be implemented, which is based on the configuration of the Struts.xml file. The syntax format for defining interceptors is as follows:<interceptor name= "Interceptor name" class= "interceptor corresponding Java type"/>configuration of the interceptor stack<interceptors><interceptor-stack name= "Interceptor stack name" ><interceptor-ref name= "Interceptor name"/></interceptor></interceptors>examples of interceptors:an interceptor that implements text filteringAction:
public class Contentaction extends actionsupport{      private string name;//comment person      private string content;//comment content            Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} @Override public    String execute () throws Exception {    return SUCCESS;}    }

Interceptor class:
public class Contentinterceptor extends abstractinterceptor{@Overridepublic String intercept (actioninvocation arg0) Throws Exception {        Object obj = arg0.getaction ();//Gets an instance of action        if (obj! = null) {        if (obj instanceof contentaction) {        contentaction CA = (contentaction) obj;//instantiate contentaction class        String content = Ca.getcontent (); /Get user-submitted comment information        int startIndex = content.indexof (' person ');//Detect characters where the person appears        //intercept three strings from the beginning of the person string        str = Content.substring (Startindex,startindex + 3);        If the user comments include the words to be filtered if        (Str.equals ("bad character")) {        content = Content.replaceall ("Poor character", "*");//Replace the text        to be filtered with * Ca.setcontent (content);//Assign the contents of the replacement value to the "Text" property        }        return Arg0.invoke ();        } else{        return action.login;        }        } return action.login;}        }

An important step in the configuration of the Struts.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts><constant name=" struts.i18n.encoding "value=" UTF-8 "/ >   <package name= "Default" extends= "Struts-default" namespace= "/" ><interceptors>     < Interceptor Name= "CONTENTITP" class= "Com.mxl.interceptor.ContentInterceptor"/>     </interceptors>     <action name= "Content" class= "com.mxl.actions.ContentAction" >      <result>/content_success.jsp</ result>      <result name= "Login" >/content_send.jsp</result>      <interceptor-ref name= " Defaultstack "/>      <interceptor-ref name=" CONTENTITP "/>     </action></package></ Struts>
Two simple pages:Content_send.xml:
<s:form action= "Content.action" method= "POST" >     <s:textfield name= "name" label= "Comment person" size= "Bayi"/>     <s:textfield name= "content" label= "comment Body" cols= "rows=/> <s:checkbox" "     arr" Name= " I have read and agree to the Dangdang community terms "/>     <s:submit type=" button "align=" center "/>    </s:form>
CONTENT_SUCCESS.JSP:
<table cellpadding= "0" cellspacing= "0" border= "0" align= "left" >      <tr style= "line-height:30px;" >      <td style= "font-size:14px;font-weight:bold;" align= "left" >           comments on Spring's Getting started classic      </td>< /tr>      <tr>       <td style= "FONT-SIZE:12PX;" >         Reviewers: <s:property value= "name"/>       </td>      </tr>      <tr>         <td style= " font-size:12px ">           comment text: <s:property value=" Content "/>         </td>      </tr>    </ Table>
do not forget to add in the beginning place, <%@ taglib prefix= "s" uri= "/struts-tags"%>
examples of Interceptor method filtering:Interceptor Class:
public class Logininterceptor extends methodfilterinterceptor{      @Override    protected String dointercept ( Actioninvocation arg0) throws Exception {          Map session=arg0.getinvocationcontext (). getsession ();//Get Session Object          String uname = (string) session.get ("username");//Gets the username object in the session and assigns a value to the uname variable          System.out.println (uname + "xxxxxxxxxxxxx");          if (uname! = null &&!uname.equals ("")) {//detects the value of the uname variable, if it is not null or is not "", then perform the subsequent Operation          return Arg0.invoke ();          } else{//Otherwise, re-login          session.put ("ErrorMsg", "You have not logged in, please login!") ");          return action.login;}}    }

Action class:
public class Useraction extends actionsupport{      private String username;      Private String pwd;            Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String getpwd () {return pwd;} public void SetPwd (String pwd) {this.pwd = pwd;} @Override public    String execute () throws Exception {      return SUCCESS;    } Public String Login () {if ("admin". Equals (Username.trim ())) {Actioncontext AC = Actioncontext.getcontext (); Ac.getsession (). Put ("username", username); return SUCCESS;} Else{this.addfielderror ("username", "username/password Error"); return LOGIN;}}

Configuration in Struts.xml:
<interceptors>       <interceptor name= "MYITP" class= "Com.mxl.interceptor.LoginInterceptor"/>   < /interceptors>   <action name= "Timer" class= "com.mxl.actions.TimerAction" >      <result>/ index.jsp</result>      <interceptor-ref name= "Timer"/>   </action>   <action name= " Login "class=" com.mxl.actions.UserAction ">   <result>/success.jsp</result>   <result name= "Login" >/login.jsp</result>   <interceptor-ref name= "Defaultstack"/>   <interceptor-ref Name= "MYITP" >        <param name= "Excludemethods" >login</param>   </interceptor-ref>   </action>
Two pages:login.jsp:
<font color= "Red" style= "font-size:12px" ><s:property value= "#session. ErrorMsg"/></font>     <s:form action= "Login!login.action" method= "POST" >        <s:textfield name= "username" label= "user name" size= "20"/ >        <s:password name= "pwd" label= "password" size= "/> <s:submit type=  " button "value=" Login "/>     </s:form>
SUCCESS.JSP:
<s:if test= "#session. Username==null" ><font color= "Red" > You have not logged in, can not do anything on this site, please <s:a href= "Login.action" Namespace= "/" > Login </s:a>! </font></s:if><s:else>    Welcome: <s:property value= "#session. Username"/></s:else>






Introduction and configuration usage of interceptors in struts2

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.