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();
}
上一篇:windows平台时间函数性能比较QueryPerformanceCounter,GetTickCount,ftime,time,GetLocalTime,GetSystemTimeAsFileTime


下一篇:运用SqlSugar框架+Axios写的增删查案例