工作中的需要,第一次写struts2拦截器,是一个登陆拦截器,当用户在url中输入网站链接时,先判断该用户是否登录,主要分为以下几个步骤
1.将struts.xml分成两个,登陆方法相关的.do写在struts.xml中,登陆以后的.do写在struts1.xml中
将struts.xml分解成struts.xml和struts1.xml
<include file="struts1.xml"/>
<pre name="code" class="html">2.写登陆拦截器:LoginInterceptor
public class LoginInterceptor extends AbstractInterceptor{
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(
ServletActionContext.HTTP_REQUEST);
HttpSession session = request.getSession();
String userid = (String) session.getAttribute("userid");//通过session中是否存在userid来判断用户是否登录
if (userid == null || userid.trim().equals("null") || userid.trim().equals("")) {
return Action.LOGIN;//返回登陆画面
}
return invocation.invoke();返回url中的.do
}
}
3.在struts1.xml中引入该拦截器
</pre><pre name="code" class="html">