Struts 2 Custom Interceptor Example TutorialIn struts 2, we can create the custom interceptor by implementing the Interceptor interface in a class and overriding its three life cycle method. For creating the custom interceptor, Interceptor interface must be implemented. It has three methods:
Interceptor can change the flow of the application by returning the string.Example to create custom interceptor in struts 2In this example, we are going to create custom interceptor that converts request processing data into uppercase letter. You need to follow 2 steps to create custom interceptor
1) Create an interceptor (must implement Interceptor interface)By this interceptor, we are converting the name property of action class into uppercase letter. The getStack() method of ActionInvocation returns the reference of ValueStack. We are getting the value set in the name property by findString method of ValueStack. The set method of ValueStack sets the name property by the specified value. In such case, we are converting the value of name property into uppercase letter and storing it into the valuestack. The invoke method of ActionInvocation returns the information of next resource. MyInterceptor.java2) Define the entry of interceptor in the struts.xml fileTo define the interceptor, we need to declare an interceptor first. The interceptors element of package is used to specify interceptors. The interceptor element of interceptors is used to define the custom interceptor. Here, we are defining the custom interceptor by upper. The interceptor-ref subelement of action specifies the interceptor that will be applied for this action. Here, we are specifying the defaultstack interceptors and upper interceptor. struts.xmlOther Required ResourcesThe other required resources are
1) Create form to get input (index.jsp)index.jspThis jsp page creates a form using struts UI tags. It receives name from the user. 2) Create the action classIt is the simple action class containing name property with its setter and getter methods. Login.java3) Create view componentThis jsp page displays the name input by the user. welcome.jspNext TopicStruts2 Params Interceptor Example |