您的位置:首页 > 编程语言 > Java开发

struts2 拦截器验证是否登录

2014-03-11 11:26 344 查看
前几天做了一个项目,需要在调用action之前进行验证是否未登录用户。写了一个拦截器记录一下:

登录后把用户的信息存入session当中

if (checkUser.getPassword().equals(tqUser.getPassword())) {
HttpSession session = ServletActionContext.getRequest().getSession(true);
session.setAttribute("UserInfo", checkUser);
return SUCCESS;
}


写拦截器LoginInteceptor 继承 AbstractInterceptor 代码如下:
package com.taoqu.inteceptor;

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 LoginInteceptor extends AbstractInterceptor{

@Override
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub

ActionContext ctx = invocation.getInvocationContext();
Map session = ctx.getSession();

Object user = session.get("UserInfo");
if(user != null){
return invocation.invoke();
}
ctx.put("tip", "您还没有登录,请登录或注册先亲。。");
return "login";
}
}


struts.xml文件中修改配置文件中的配置信息,声明一个拦截器,然后再需要拦截的action中标明我们在执行之前要过一下这个拦截器,看看是否用户登录如果登录了才能执行下一步,否则跳转到login

<package name="intrest" extends="struts-default">
<interceptors>
<interceptor name="authority" class="com.taoqu.inteceptor.LoginInteceptor" />
</interceptors>
<!--设置全局的跳转 -->
<global-results>
<result name="login">/login.jsp</result>
</global-results>
<!-- 跳转到发布兴趣 -->
<action name="hrefPublishIntrest" class="IntrestAction">
<interceptor-ref name="authority"/>
<result>/build.jsp</result>
</action>
<!-- 发布兴趣 -->
<action name="publishIntrest" class="IntrestAction" method="publishIntrest">
<!-- <interceptor-ref name="defaultStack"/> -->
<interceptor-ref name="authority"/>
<result name="input">/error.jsp</result>
<result name="success" type="redirect">/findcreatins.action</result>
</action>

...............


写一个记录一下,大神们可以拍砖。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java struts2 interceptor