Struts2 Framework Learning VI: Understanding and using interceptors

Source: Internet
Author: User
Tags auth exception handling file upload

Preface

Interceptors are a core feature of the STRUTS2 framework, and understanding and using interceptors can help you use Struts2 more flexibly. Interceptors are somewhat similar to, but not identical to, the filters in the servlet. Because the interceptor is more like a pluggable component in Struts2, it is done around action and result, and can be used before and after a method call. Through the STRUTS2 workflow (you will also see a request in detail in the execution process in Struts2), you can find a number of interceptors before invoking an action, which are passed before the specific action is executed. For each interceptor, it is possible to return directly, thus terminating the remaining interceptors.

from the Struts2 workflow.

First, take a look at a picture that has been intercepted from the official:

As you can see from the diagram, a specific request to the action needs to go through multiple interceptors, and after the action has been processed, the subsequent interceptors will continue to execute and end up in the browser. The STRUTS2 workflow is as follows: The request is sent to Strutsprepareandexecutefilter Strutsprepareandexecutefilter to determine if the request is a STRUTS2 request, and if so, enter the 3rd step In the case of a STRUTS2 request, the request is given to Actionproxy, which is the proxy class for the action Actionproxy creates a actioninvocation instance and initializes it before executing the specific action. Actionproxy will involve a call to the relevant interceptor after the action call ends, the corresponding return result is obtained based on the result configuration object of the action in the Struts.xml file. After invoking the Execute method, render the returned result to the following interceptor to return the result to the browser

From the entire request processing process, interceptors are the key to processing. OK, with the above request process, we know how an interceptor works in Struts2. Let's start by writing a simple intercept and learn to use interceptors.

a simple interceptor.

There are two main ways: Implement Interceptor Interface Inheritance Abstractinterceptor abstract class

Writing your own interceptor must implement the Com.opensymphony.xwork2.interceptor.Interceptor interface, which has three methods: Init (), Destroy (), intercept (). The Init method is called prior to the Intercept method after the interceptor instance is created, primarily for initializing the resources required by the interceptor, and the Destroy method is called before the Interceptor instance is destroyed to destroy Init-initialized allocated resources The Intercept method is called before the action executes, and the state of the action can be obtained through the invocation object, which makes the required interception operations different depending on the state.

The following is an example of implementing the Interceptor interface to write an interceptor that calculates the time that the action execution method executes. The code is as follows:

Package Interceptor;

Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.Interceptor;

public class Timeintercptor implements interceptor {

    private static final long serialversionuid = 1L;

    @Override public void
    Destroy () {
    }

    @Override public
    void init () {
    }

    @Override
    public String Intercept (actioninvocation invocation) throws Exception {
        long start = System.currenttimemillis ();
        Execute method for executing action
        String result = Invocation.invoke ();
        Long end = System.currenttimemillis ();
        System.out.println ("The time to execute the Execute method is" + (End-start));
        return result;
    }

}

When you write an action and configure it in the Struts.xml configuration file, you can test it in a browser to get the exact time to execute the Execute method. When writing the Interceptor class, it is important to note that there should be no instance variable in the interceptor because the interceptor is stateless, and the stateless explanation is that if the interceptor is stateful, the interceptor's state is unpredictable when it accesses the interceptor instance at the same time as the multi-threaded device.

So far, we've learned how to write a simple interceptor, and here are some of the interceptors that come with the interceptor.

Struts2 in-band Interceptor

The self-contained interceptor can be found in the Struts-default.xml file, mainly: execandwait (this interceptor allows the action that needs to run for a long time to run in the background and show the user Progress information) exception (mainly for exception handling) FileUpload (for file upload) i18n (internationalized Support) logger (log, record action start from end log) Modeldriven (support model-driven Interceptor) validation (define your own authenticator)

interceptors that develop security verification features

In daily development, it is common to have login verification. The main function of the interceptor developed here is that if the user is not logged in, it prompts for no sign-in information and returns to the login page. If the user is already logged in, the resource is displayed. This article mainly introduces the development steps of interceptors in actual development.

Step 1: Write the basic page

Login page:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%@ taglib uri= "/struts-tags" Prefix= "s"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Login Success Page:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%@ taglib uri= "/struts-tags" Prefix= "s"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Resources page:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%
String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Step Two: Write action
Loginaction2.java:

Package action;

Import Java.util.Map;

Import Org.apache.struts2.interceptor.SessionAware; Import Bean.

User;

Import Com.opensymphony.xwork2.ActionSupport; public class LoginAction2 extends Actionsupport implements Sessionaware {private static final long Serialversionuid

    = 1L;
    private user user;

    Private Map<string, object> session;
    Access login.jsp public String input () throws exception{return input via login!input; } @Override Public String execute () throws Exception {if ("admin". Equals (User.getusername ()) && "
            Admin ". Equals (User.getpassword ())) {System.out.println (User.getusername () +" = "+ User.getpassword ());
            Session.put ("user", user);
        return SUCCESS; }else{addactionerror ("Login failed.
            ");
        return INPUT;
    }} @Override public void Setsession (Map<string, object> session) {this.session = session; } public User GetUser () {return user;
    public void SetUser (user user) {this.user = user;
 }
}

Step four: Writing interceptors

The code is as follows:

Package interceptor;

Import Java.util.Map;
Import Com.opensymphony.xwork2.ActionContext;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.ActionSupport;

Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor; 

    public class Authenticationinterceptor extends Abstractinterceptor {private static final long serialversionuid = 1L; /** * Block verification of login or not */@Override public String intercept (actioninvocation invocation) throws Excepti
        On {Actioncontext context = Actioncontext.getcontext ();
        Map<string, object> session = Context.getsession ();
        Object user = Session.get ("user"); if (user = = null) {//If the user is not logged in, return to the login page and add an error message Actionsupport action = (actionsupport) Invocation.geta
            Ction (); Action.addactionerror ("You are not logged in, please login first.")
            "); Return action.
        LOGIN;
        }else{//If the user is already logged in, execute the following interceptor method return Invocation.invoke (); }
    }

}
 

Step five: Configure in Struts.xml

    <interceptors> <interceptor name= "auth" class= "interceptor. Authenticationinterceptor "/> <interceptor-stack name=" Securitystack "> <intercep Tor-ref name= "Defaultstack"/> <interceptor-ref name= "auth"/> </interceptor-sta ck> </interceptors> <global-results> <result name= "Login" >/web-inf/pages/l ogin.jsp</result> </global-results> <action name= "login2" class= "action. LoginAction2 "> <result name=" input ">/WEB-INF/pages/login.jsp</result> <result&gt ;/web-inf/pages/success.jsp</result> </action> refer to the above interceptor for protected resources <action name= "resource" Class= "action. Resourceaction "> <result>/WEB-INF/pages/resource.jsp</result> <interceptor-ref N
 Ame= "Annotatedstack"/> </action>

Step Six: Enter Http:localhost:8090/struts2/login2!input in the browser to test.

At this point, a security-proven interceptor has been developed.

Interceptor Summary

From the development process, the role of interceptors is to intercept operations in a State of action, and the use of interceptors makes it easier to handle business logic. There are annotations in addition to the above-mentioned development interceptors, but one obvious disadvantage of annotation is that it is not conducive to the reuse of code, and the bottom of the annotation is done using reflection, so using annotation development, performance is a problem worth considering.

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.