Struts 2 自定义拦截器创建与使用

来源:互联网 发布:java graphics2d 旋转 编辑:程序博客网 时间:2024/05/22 07:48

Strus2 提供了Interceptor 接口,通过该接口可以很容易的实现一个拦截器类。开发者只需要直接或间接实现Interceptor接口

public interface Interception extends Serializable{

void destroy();

void init();

String intercept(ActionInvocation  invccation) throws Exception;

}

init(); 由拦截器之前调用,主要用于初始化系统资源。

destroy();与init()相反,用于拦截器之后执行销毁资源。

intercept();拦截器的核心方法,实现具体的拦截操作,返回字符串作为逻辑视图,与Action一样,如果拦截器能够成功调用Action,则Action 种的execute()方法返回一个字符串类型值,将器作为逻辑视图返回,反之返回一个开发者自定义的一个逻辑视图。

用户登陆拦截器:

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class interfac extends AbstractInterceptor {
public String intercept(ActionInvocation ai) throws Exception {
Map m = (Map) ai.getInvocationContext().getParameters();
String[] username = (String[]) m.get("username");
String u = username[0];
if (u != null && u.length() > 0) {
return ai.invoke();
} else {
                       ActionContext ac = ai.getInvocationContext();
ac.put("sorry", "您还没有登陆");
return Action.LOGIN;
}


}
}

struts.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEstruts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

<includefile="struts-default.xml"/>

<packagename="login"extends="struts-default"namespace="/login">

<interceptors>

<interceptorname="login"class="com.poba.model.interfac"/>

<interceptorname="public"class="com.poba.model.Myintercept"/>

<interceptor-stackname="loginchect">

<interceptor-refname="login"/>

<interceptor-refname="defaultStack"/>

</interceptor-stack>

</interceptors>

<default-interceptor-refname="loginchect"/>

<actionname="login"class="com.poba.model.LoginAction"method="checkLogin">

<resultname="success"> /index.jsp</result>

<resultname="login">/login.jsp</result>

<resultname="input">/login.jsp</result>

</action>

</package>

</struts> 


原创粉丝点击