Struts 2 создает собственный перехватчик
В этом уроке показано, как создать собственный перехватчик в Struts 2.
Сводные шаги:
-
Создать класс реализуетcom.opensymphony.xwork2.interceptor.Interceptor.
-
Реализуйте методintercept(ActionInvocation invocation).
-
Настройте перехватчик вstruts.xml.
-
Свяжите это с действием.
Struts 2 interceptors
Struts 2 поставляется с множеством готовых перехватчиков, убедитесь, что вы проверили списокavailable Struts 2 interceptors, прежде чем создавать свой собственный перехватчик.
Полный пример создания собственного перехватчика:
1. действие
Простое действие, чтобы переслать запрос пользователя и распечатать сообщение.
HelloAction.java
package com.example.common.action; import com.opensymphony.xwork2.ActionSupport; public class HelloAction extends ActionSupport{ public String execute() throws Exception { System.out.println("HelloAction execute() is called"); return SUCCESS; } }
2. истребитель-перехватчик
Полный пример перехватчика.
PrintMsgInterceptor.java
package com.example.common.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class PrintMsgInterceptor implements Interceptor{ //called during interceptor destruction public void destroy() { System.out.println("CustomInterceptor destroy() is called..."); } //called during interceptor initialization public void init() { System.out.println("CustomInterceptor init() is called..."); } //put interceptor code here public String intercept(ActionInvocation invocation) throws Exception { System.out.println("CustomInterceptor, before invocation.invoke()..."); String result = invocation.invoke(); System.out.println("CustomInterceptor, after invocation.invoke()..."); return result; } }
Explanation
Класс перехватчика должен реализовыватьcom.opensymphony.xwork2.interceptor.Interceptor interface. Во время инициализации перехватчика вызываетсяinit(); вызывается уничтожение перехватчикаdestroy(). Наконец, поместите весь код перехватчика, который выполняет эту работу, в методintercept(ActionInvocation invocation).
invocation.invoke()
В методе перехватчика intercept () выmust called the invocation.invoke() и возвращаете его результат. Этот метод отвечает за вызов следующего перехватчика или действия. Действие не будет продолжено без вызова методаinvocation.invoke().
destroy() is not reliable
Не рекомендуется помещать какой-либо код внутриdestroy(), потому что этот метод ненадежен. Когда ваш сервер приложений принудительно завершает работу или завершается с помощью команды,destroy() не будет вызываться.
3. struts.xml
Настройте перехватчик в файлеstruts.xml.
pages/hello.jsp
4. Demo
Во время инициализации сервера вызывается метод перехватчикаinit().
INFO: Overriding property struts.i18n.reload - old value: false new value: true 15 Julai 2010 11:37:42 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true CustomInterceptor init() is called... 15 Julai 2010 11:37:42 AM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8080 15 Julai 2010 11:37:42 AM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 15 Julai 2010 11:37:42 AM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/20 config=null 15 Julai 2010 11:37:42 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 994 ms
При доступе к действию через URL:http://localhost:8080/Struts2Example/helloAction.action
INFO: Overriding property struts.i18n.reload - old value: false new value: true 15 Julai 2010 11:37:42 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Overriding property struts.configuration.xml.reload - old value: false new value: true CustomInterceptor init() is called... 15 Julai 2010 11:37:42 AM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8080 15 Julai 2010 11:37:42 AM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 15 Julai 2010 11:37:42 AM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/20 config=null 15 Julai 2010 11:37:42 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 994 ms CustomInterceptor, before invocation.invoke()... HelloAction execute() is called CustomInterceptor, after invocation.invoke()...