struts2中自定义拦截器的简单应用

最近了解了自定义拦截器的应用,发现这个东西可以很好地解决登录状态的问题,这里做一个简单应用练手。

之前写过一个登录界面,这里先简单说一下,登录表单提交到login.action中进行处理,然后再AccountAction类中的login方法里提取表单数据进行处理(这里用的是模型驱动封装)。这样做有一个问题就是,如果我直接访问login.action,由于请求中没有表单数据,在后续的操作中就会出现空指针错误。所以使用拦截器来解决,在拦截器中判断表单中的数据是否为空,如果为空就跳转到登录界面,如果不为空才执行AccountAction中的方法。

下面来具体实现。

先新建一个类,这里叫AccountInterceptor,这个类要继承MethodFilterInterceptor(com.opensymphony.xwork2.interceptor.MethodFilterInterceptor),并重写里面的doIntercept方法。在doIntercept方法中实现自定义拦截器要实现的操作。我的登录表单里有username和password,为了省事就只取了一个username,也能达到效果。

public class AccountInterceptor extends MethodFilterInterceptor {

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Object object = request.getParameter("username");
//		System.out.println("username:" + String.valueOf(object));
		
		if(object == null) {
			return "needToLogin";
		} else {
			return invocation.invoke();
		}
	}

}
写完拦截器后还要配置Struts.xml文件,首先在 package中声明这个拦截器。

<!-- 声明一个拦截器 -->
		<interceptors>
			<interceptor name="accountInterceptor" class="com.web.interceptor.AccountInterceptor"></interceptor>
		</interceptors>
然后在要使用拦截器的action标签中配置该拦截器。

<action name="login" class="com.web.action.AccountAction" method="login">
			<interceptor-ref name="accountInterceptor"></interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<result name="needToLogin" type="redirect">/login.jsp</result>
			<result name="success" >/accountDetail.jsp</result>
			<result name="failed" >/login.jsp</result>
		</action>
注意,不要忘了配置struts本身的默认拦截器。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值