栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot中登录后关于cookie和session拦截问题的案例分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot中登录后关于cookie和session拦截问题的案例分析

一、前言

1、简单的登录验证可以通过Session或者cookie实现。
2、每次登录的时候都要进数据库校验下账户名和密码,只是加了cookie 或session验证后;比如登录页面A,登录成功后进入页面B,若此时cookie过期,在页面B中新的请求url到页面c,系统会让它回到初始的登录页面。(类似单点登录sso(single sign on))。
3、另外,无论基于Session还是cookie的登录验证,都需要对HandlerInteceptor进行配置,增加对URL的拦截过滤机制。

二、利用cookie进行登录验证

1、配置拦截器代码如下:

public class cookiendSessionInterceptor implements HandlerInterceptor {  

@Override  
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {   
  log.debug("进入拦截器");   
  cookie[] cookies = request.getcookies();   
  if(cookies!=null && cookies.length>0){    
   for(cookie cookie:cookies) {    
     log.debug("cookie===for遍历"+cookie.getName());     
     if (StringUtils.equalsIgnoreCase(cookie.getName(), "isLogin")) {      
      log.debug("有cookie ---isLogin,并且cookie还没过期...");      
      //遍历cookie如果找到登录状态则返回true继续执行原来请求url到controller中的方法      
      return true;     
 }    
      }   
     }   
   log.debug("没有cookie-----cookie时间可能到期,重定向到登录页面后请重新登录。。。");   
   response.sendRedirect("index.html");   
   //返回false,不执行原来controller的方法   
   return false;  }  

 @Override  
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 
  }  
 @Override 
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 
  } 

}

2、在Springboot中拦截的请求不管是配置监听器(定义一个类实现一个接口HttpSessionListener )、过滤器、拦截器,都要配置如下此类实现一个接口中的两个方法。
代码如下:

@Configuration 
public class WebConfig implements WebMvcConfigurer {  
// 这个方法是用来配置静态资源的,比如html,js,css,等等  
@Override  
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
 } 

 // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效 
@Override  
public void addInterceptors(InterceptorRegistry registry) {   
//addPathPatterns("login",   
     "*.html",   
     "*.js",   
     "*.css",   
     "*.jpg"); 
 } 

 }

3.前台登录页面index.html(我把这个html放在静态资源了,也让拦截器放行了此路由url)
前端测试就是一个简单的form表单提交

 

4、后台控制层Controller业务逻辑:登录页面index.html,登录成功后 loginSuccess.html。
在loginSuccess.html中可提交表单进入次页demo.html,也可点击“退出登录”后台清除没有超时的cookie,并且回到初始登录页面。

@Controller 
@Slf4j 
@RequestMapping(value = "/") 
public class TestcookieAndSessionController {  
@Autowired  JdbcTemplate jdbcTemplate;  
  

@PostMapping(value = "login")  
public String test(HttpServletRequest request, HttpServletResponse response, @RequestParam("name1")String name,@RequestParam("pass1")String pass) throws Exception{   
 try {    
 Map result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass});    
  if(result==null || result.size()==0){     
   log.debug("账号或者密码不正确或者此人账号没有注册");     
   throw new Exception("账号或者密码不正确或者此人账号没有注册!");    
  }else{     
   log.debug("查询满足条数----"+result);     
   cookie cookie = new cookie("isLogin", "success");     
   cookie.setMaxAge(30);     
   cookie.setPath("/");    
   response.addcookie(cookie);     
   request.setAttribute("isLogin", name);     
   log.debug("首次登录,查询数据库用户名和密码无误,登录成功,设置cookie成功");     
   return "loginSuccess";    }   
 } catch (DataAccessException e) {    
   e.printStackTrace();    
   return "error1";   
  } 
 } 
 
  
@PostMapping(value = "sub")  
public String test() throws Exception{  
 return "demo";  
 }  
 
@RequestMapping(value = "exit",method = RequestMethod.POST)  
public String exit(HttpServletRequest request,HttpServletResponse response) throws Exception{   
 cookie[] cookies = request.getcookies();   
 for(cookie cookie:cookies){   
 if("isLogin".equalsIgnoreCase(cookie.getName())){    
  log.debug("退出登录时,cookie还没过期,清空cookie");     
  cookie.setMaxAge(0);     
  cookie.setValue(null);     
  cookie.setPath("/");    
  response.addcookie(cookie);    
  break;    
  }   
  }   
 //重定向到登录页面   
 return "redirect:index.html";  
  } 

}

5、效果演示:
①在登录“localhost:8082”输入账号登录页面登录:

②拦截器我设置了放行/login,所以请求直接进Controller相应的方法中:
日志信息如下:

下图可以看出,浏览器有些自带的不止一个cookie,这里不要管它们。

③在loginSuccess.html,进入次页demo.html。cookie没有过期顺利进入demo.html,并且/sub方法经过拦截器(此请求请求头中携带cookie)。
过期的话直接回到登录页面(这里不展示了)

④在loginSuccess.html点击“退出登录”,后台清除我设置的没过期的cookie=isLogin,回到登录页面。

三、利用Session进行登录验证

1、修改拦截器配置略微修改下:

Interceptor也略微修改下:还是上面的preHandle方法中:

2.核心
前端我就不展示了,就是一个form表单action="login1"
后台代码如下:

 
@RequestMapping(value = "login1",method = RequestMethod.POST)  
public String testSession(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("name1")String name,      
@RequestParam("pass1")String pass) throws Exception{   
 try {   
 Map result= jdbcTemplate.queryForMap("select * from userinfo where name=? and password=?", new Object[]{name, pass});    
  if(result!=null && result.size()>0){     
  String requestURI = request.getRequestURI();     
  log.debug("此次请求的url:{}",requestURI);     
  HttpSession session = request.getSession();     
  log.debug("session="+session+"session.getId()="+session.getId()+"session.getMaxInactiveInterval()="+session.getMaxInactiveInterval());     
  session.setAttribute("isLogin1", "true1");    
  }   
 } catch (DataAccessException e) {    
  e.printStackTrace();   
  return "error1";  
 }  
 return "loginSuccess"; 
 } 

 //登出,移除登录状态并重定向的登录页  
@RequestMapping(value = "/exit1", method = RequestMethod.POST)  
public String loginOut(HttpServletRequest request) {   
 request.getSession().removeAttribute("isLogin1");   
 log.debug("进入exit1方法,移除isLogin1");   
 return "redirect:index.html";  
 }
 }

日志如下:可以看见springboot内置的tomcat中sessionid就是请求头中的jsessionid,而且默认时间1800秒(30分钟)。
我也不清楚什么进入拦截器2次,因为我login1设置放行了,肯定不会进入拦截器。可能是什么静态别的什么资源吧。

session.getId()=F88CF6850CD575DFB3560C3AA7BEC89F==下图的JSESSIONID

//点击退出登录,请求退出url的请求头还是携带JSESSIONID,除非浏览器关掉才消失。(该session设置的属性isLogin1移除了,session在不关浏览器情况下或者超过默认时间30分钟后,session才会自动清除!)

四、完结

到此这篇关于Springboot中登录后关于cookie和session拦截案例的文章就介绍到这了,更多相关Springboot登录关于cookie和session拦截内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/132380.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号