Struts2通过注解来实现拦截器
首页写一个自定义的拦截器类MyInterceptor,实现Interceptor接口(或者继承自AbstractInterceptor)的类。
Interceptor接口声明了三个方法:
public interface Interceptor extends Serializable { void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception;}
public abstract class AbstractInterceptor implements Interceptor { public void init() { } public void destroy() { } public abstract String intercept(ActionInvocation invocation) throws Exception;}
package com.sunny.action;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;public class MyInterceptor implements Interceptor {/** * */private static final long serialVersionUID = 1L;@Overridepublic void init() {System.out.println("init");}@Overridepublic String intercept(ActionInvocation invoker) throws Exception {System.out.println("intercept");String result = invoker.invoke();return result;}@Overridepublic void destroy() {System.out.println("destory");}}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><!-- 请求参数的编码方式 --><constant name="struts.i18n.encoding" value="UTF-8" /><package name="custom-default" extends="struts-default"><interceptors><interceptor name="annotationInterceptor" /><interceptor-stack name="annotatedStack"><interceptor-ref name="annotationInterceptor" /><interceptor-ref name="defaultStack" /></interceptor-stack></interceptors> <!-- 设置全局 全局默认的拦截器栈--> <default-interceptor-ref name="annotatedStack"></default-interceptor-ref> </package></struts>
package com.sunny.action;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.ExceptionMapping;import org.apache.struts2.convention.annotation.ExceptionMappings;import org.apache.struts2.convention.annotation.InterceptorRef;import org.apache.struts2.convention.annotation.InterceptorRefs;import org.apache.struts2.convention.annotation.Namespace;import org.apache.struts2.convention.annotation.ParentPackage;import org.apache.struts2.convention.annotation.Result;import com.opensymphony.xwork2.ActionSupport;import com.sunny.entity.Users;@ParentPackage("custom-default")@Namespace("/login")// 公共异常捕获@ExceptionMappings({ @ExceptionMapping(exception = "java.lang.Exception", result = "exception") })// 拦截器@InterceptorRefs({ @InterceptorRef("annotatedStack") })public class LoginAction extends ActionSupport {/** * */private static final long serialVersionUID = 1L;private Users users;public Users getUsers() {return users;}public void setUsers(Users users) {this.users = users;}@Action(value = "add", results = {@Result(name = "success", location = "/a.jsp"),@Result(name = "error", location = "/index.jsp") })@Overridepublic String execute() throws Exception {if (users.getUsername().equals("sunny")&& users.getPassword().equals("sunny")) {return "success";} else {return "error";}}}