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

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

<?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>

<include file="struts-default.xml"/>

<package name="login" extends="struts-default" namespace="/login">

<interceptors >

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

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

<interceptor-stack name="loginchect">

<interceptor-ref name="login"/>

<interceptor-ref name="defaultStack"/>

</interceptor-stack>

</interceptors>

<default-interceptor-ref name="loginchect"/>

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

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

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

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

</action>

</package>

</struts> 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值