最近了解了自定义拦截器的应用,发现这个东西可以很好地解决登录状态的问题,这里做一个简单应用练手。
之前写过一个登录界面,这里先简单说一下,登录表单提交到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本身的默认拦截器。