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

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

2015-11-20 14:19 411 查看
目的:测试开发时,为了减少用户登入这个繁琐的登入验证,就用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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: