struts2自定义拦截器与cookie整合实现用户免重复登入

目的:测试开发时,为了减少用户登入这个繁琐的登入验证,就用struts2做了个简单的struts2拦截器,涉及到了与cookie整合,具体的看代码

 

结构(两部份)=struts2.xml+自定义拦截器对象

 

配置文件

		<!-- 自定义拦截栈与拦截器 -->
		<interceptors>
			<interceptor name="visitInterceptor" class="cn.kjkj.web.ema.view.interceptor.VisitInterceptor" />
			<interceptor name="cookieInterceptor" class="cn.kjkj.web.ema.view.interceptor.CookieInterceptor" />
			<interceptor-stack name="MyStack">
				<interceptor-ref name="cookieInterceptor" />
				<interceptor-ref name="visitInterceptor" />
				<interceptor-ref name="paramsPrepareParamsStack" />
			</interceptor-stack>
		</interceptors>

		<!-- 设置默认拦截栈 -->
		<default-interceptor-ref name="MyStack" />

 

    自定义拦截器具体实现

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import org.springframework.beans.factory.annotation.Autowired;

import cn.kjkj.web.ema.domain.User;
import cn.kjkj.web.ema.service.UserService;
import cn.kjkj.web.ema.view.action.BaseAction;
import cn.kjkj.web.ema.view.action.LoginAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**登入时间缓存拦截器
 * */
@SuppressWarnings("serial")
public class CookieInterceptor extends AbstractInterceptor  {
	@Autowired
	private UserService userService;
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
	/**登入拦截*/
		Object action=invocation.getAction();  
		Map<String, Object> session=invocation.getInvocationContext().getSession();
		Cookie [] cookies= BaseAction.getRequest().getCookies();
		//System.out.println(cookies!=null);
		String account=null;
		String  password=null;
		if(!(action instanceof LoginAction)){ //判断是否正在登入
			if(session.get("usermessage")!=null){
				return invocation.invoke();
			}else{
				if(cookies!=null){
					
				for(Cookie c:cookies){
					if(c.getName().equalsIgnoreCase("username")){
					if(c!=null){
						account=c.getValue();
					}
					}else if(c.getName().equalsIgnoreCase("password")){
						if(c!=null){
							password=c.getValue();
						}
					}
				}
				if(account!=null&&password!=null){
					User u=new User(account, password);
					List<User> list=userService.checkMessage(u);
					if(list.size()==1){
						session.put("usermessage", list.get(0));
						return BaseAction.MAIN;
					}
					}
				}
			}
		}
		
		return invocation.invoke();
	}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值