struts2 拦截器验证是否登录

前几天做了一个项目,需要在调用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>	

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



写一个记录一下,大神们可以拍砖。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值