springboot项目:登录 登录aop拦截 使用Redis与cookie 进行设置获取清除操作
登录、登出:
第一步:在pom文件中引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
第二步:在application.yml文件中进行Redis配置
spring: redis:host: 192.168.1.104port: 6379
第三步:编写cookie工具类
package com.payease.utils;import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map;/*** Cookie工具类* @Created By liuxiaoming* @CreateTime 2017/12/6 下午4:31**/ public class CookieUtil {/*** 设置cookie* @param response* @param name* @param value* @param maxAge*/public static void set(HttpServletResponse response,String name,String value,int maxAge){Cookie cookie = new Cookie(name, value); //设置cookie的key和value值cookie.setPath("/"); //路径cookie.setMaxAge(maxAge); //过期时间response.addCookie(cookie); //添加cookie }/*** 获取cookie* @param request* @param name* @return*/public static Cookie get(HttpServletRequest request,String name){Map<String, Cookie> cookieMap = readCookieMap(request);if(cookieMap.containsKey(name)){ //判断cookieMap是否含有该keyreturn cookieMap.get(name);}else{return null;}}/*** 将cookie封装成map* @param request* @return*/private static Map<String, Cookie> readCookieMap(HttpServletRequest request){Map<String, Cookie> cookieMap = new HashMap<>();Cookie[] cookies = request.getCookies(); //获取所有的cookie值if(cookies != null){for (Cookie cookie : cookies){cookieMap.put(cookie.getName(),cookie);}}return cookieMap;} }
第四步:分别设置cookie的常量和Redis的常量
cookie常量:
package com.payease.constant;/*** cookie常量* @Created By liuxiaoming* @CreateTime 2017/12/6 下午4:38**/ public interface CookieConstant {String TOKEN = "token";Integer EXPIRE = 7200; }
Redis常量:
package com.payease.constant;/*** redis常量* @Created By liuxiaoming* @CreateTime 2017/12/6 下午4:21**/ public interface RedisConstant {String TOKEN_PREFIX = "token_%s";Integer EXPIRE = 7200; //2小时 }
第五步:编写调用
package com.payease.controller;import com.payease.config.ProjectUrlConfig; import com.payease.constant.CookieConstant; import com.payease.constant.RedisConstant; import com.payease.dataobject.SellerInfo; import com.payease.enums.ResultEnum; import com.payease.service.SellerService; import com.payease.utils.CookieUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit;/*** 卖家用户* Created by liuxiaoming* 2017-12-06 下午05:35*/ @Controller @RequestMapping("/seller") public class SellerUserController {@Autowiredprivate SellerService sellerService;@Autowiredprivate StringRedisTemplate redisTemplate;@Autowiredprivate ProjectUrlConfig projectUrlConfig;@GetMapping("/login")public ModelAndView login(@RequestParam("openid") String openid,HttpServletResponse response,Map<String, Object> map) {//1. openid去和数据库里的数据匹配SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);if (sellerInfo == null) {map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());map.put("url", "/sell/seller/order/list");return new ModelAndView("common/error");}//2. 设置token至redisString token = UUID.randomUUID().toString();Integer expire = RedisConstant.EXPIRE;redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);//3. 设置token至cookie CookieUtil.set(response, CookieConstant.TOKEN, token, expire);return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");}@GetMapping("/logout")public ModelAndView logout(HttpServletRequest request,HttpServletResponse response,Map<String, Object> map) {//1. 从cookie里查询Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);if (cookie != null) {//2. 清除redis redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));//3. 清除cookieCookieUtil.set(response, CookieConstant.TOKEN, null, 0);}map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());map.put("url", "/sell/seller/order/list");return new ModelAndView("common/success", map);} }
登录拦截aop、异常捕获 :
第一步:SellerAuthorizeException异常类
package com.payease.exception;/*** @Created By liuxiaoming* @CreateTime 2017/12/8 上午10:41**/ public class SellerAuthorizeException extends RuntimeException{ }
第二步:aop拦截
package com.payease.aspect;import com.payease.constant.CookieConstant; import com.payease.constant.RedisConstant; import com.payease.exception.SellerAuthorizeException; import com.payease.utils.CookieUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest;/*** @Created By liuxiaoming* @CreateTime 2017/12/8 上午10:18**/ @Aspect @Component @Slf4j public class SellerAuthorizeAspect {@Autowiredprivate StringRedisTemplate redisTemplate;@Pointcut("execution(public * com.payease.controller.Seller*.*(..))" +"&& !execution(public * com.payease.controller.SellerUserController.*(..))")public void verify(){}@Before("verify()")public void doVerify(){ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();//查询cookieCookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);if(cookie == null){log.warn("【登陆校验】Cookie中查不到token");throw new SellerAuthorizeException();}//从Redis中查询String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));if(StringUtils.isEmpty(tokenValue)){log.warn("【登陆校验】Redis中查不到token");throw new SellerAuthorizeException();}} }
第三步:编写异常捕获类
package com.payease.handler;import com.payease.config.ProjectUrlConfig; import com.payease.exception.SellerAuthorizeException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView;/*** 异常捕获类* @Created By liuxiaoming* @CreateTime 2017/12/8 上午10:54**/ @ControllerAdvice public class SellerExceptionHandler {@Autowiredprivate ProjectUrlConfig projectUrlConfig;//拦截登录异常//http://sell.natapp4.cc/sell/wechat/qrAuthorize?returnUrl=http://sell.natapp4.cc/sell/seller/login@ExceptionHandler(value= SellerAuthorizeException.class)public ModelAndView handlerAuthorizeException(){return new ModelAndView("redirect:".concat("/seller/loginException")); // .concat(projectUrlConfig.getWechatOpenAuthorize()) // .concat("/sell/wechat/qrAuthorize") // .concat("?returnUrl=") // .concat(projectUrlConfig.getSell()) // .concat("/sell/seller/login")); } }
第四步:编写页面
<html> <head><meta charset="utf-8"><title>错误提示</title><link href="https://cdn.bootcss.com/bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body><div class="container"><div class="row clearfix"><div class="col-md-12 column"><div class="alert alert-dismissable alert-danger"><h3>登录页面</h3><form action="/sell/seller/login"><br>openid:<input type="text" name="openid"/><br><input type="submit" value="登录"/></form></div></div></div> </div></body></html>
第五步:编写controller
@GetMapping("/loginException")public ModelAndView loginException(Map<String, Object> map) {map.put("msg", ResultEnum.LOGIN_RELOAD.getMessage());map.put("url", "/sell/seller/loginPage");return new ModelAndView("common/error");}@GetMapping("/loginPage")public ModelAndView loginException() {return new ModelAndView("common/login");}
转载于:https://www.cnblogs.com/liuxiaoming123/p/7997509.html
springboot项目:登录 登录aop拦截 使用Redis与cookie 进行设置获取清除操作相关推荐
- 快速上手Springboot项目(登录注册保姆级教程)
本文章对SpringBoot开发后端项目结构做了简单介绍,并示范了使用SpringBoot+MySQL实现登录的后端功能,与本博客的另一篇文章 Vue 实现登录注册功能(前后端分离完整案例) | Ma ...
- springboot + vue 后台token生成 拦截器 redis实现 前台封装axios xueX 接口实现
后台 后台程序图片 新建token的基础类 public class Constants {public final static String TOKEN = "token";} ...
- 使用IDEA集成docker部署springboot项目及bug解决并连同redis、MySQL
流程介绍 安装docker(windows) 配置docker源加速 docker安装redis IDEA集成docker # IDEA连接docker 配置springboot项目 打包成docke ...
- 验证码及登录切面Aop拦截代码
首先定义验证码和登录监测的两个注解 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; im ...
- springboot项目使用swagger时拦截器需要放开哪些URL
1.如果不设置会导致swagger主页无法访问 2.以下url不需要拦截 /swagger-resources/*, /swagger-ui.html,/v2/api-docs, /webjars/s ...
- SpringBoot项目中计量单位与进制转换问题解决措施及数据校验怎么操作
写在前面: 继续记录自己的SpringBoot学习之旅,这次是SpringBoot应用相关知识学习记录.若看不懂则建议先看前几篇博客,详细代码可在我的Gitee仓库SpringBoot克隆下载学习使用 ...
- Springboot项目install打包-某些输入文件使用了未经检查或不安全的操作。分析与解决
目录 分析: 方法一.进行参数化(失败): 方法二.注解忽略警告(成功): 使用 -Xlint:unchecked 编译 再次分析: 方法三.安全的进行强制类型转换(成功): 分析: 初步确认是使用j ...
- Springboot项目Aop、拦截器、过滤器横向对比
前言 伟人曾经说过,没有调查就没有发言权(好像是伟人说的,不管谁说的,这句话是正确的),有些东西看着简单,张口就来,但很有可能是错的.我个人的经验是,aop.过滤器.拦截器的实现方式很简单,一学就会, ...
- 第六章:如何在SpringBoot项目中使用拦截器
拦截器对使用SpringMvc.Struts的开发人员来说特别熟悉,因为你只要想去做好一个项目必然会用到它.拦截器在我们平时的项目中用处有很多,如:日志记录(我们后续章节会讲到).用户登录状态拦截.安 ...
- SpringBoot学习-用户注册登录
1.idea创建maven项目,下面步骤按自己实际情况填写创建. 2.环境 spring.mvc等配置不需要自己写,只需配置一下数据库即可.另外,与主应用程序上下文不同的外部配置,我在根目录创建app ...
最新文章
- idea可以使用flash框架吗_这个框架厉害了,使用它几分钟就可以编写一个微信插件...
- 数学与当代生命科学(吴家睿)
- 解决mantis不能上传附件问题
- C++中变量使用前一定要初始化
- 第六节:深究事务的相关性质、隔离级别及对应的问题、死锁相关
- 牛客网【每日一题】7月21日题目精讲—区间权值
- 【kafka】消费组 死掉 kafka Marking the coordinator dead for group
- 集合 ---- 重复数
- WinStore控件之Button、HyperlinkButton、RadioButton、CheckBox、progressBar、ScrollViewer、Slider...
- Asp.Net MVC 控制器
- matlab除法使用broadcast机制要小心
- 艺体计算机教师考核细则,音体美教师考核办法
- 今天的骑行路线。。。
- 百度android离线下载,离线宝app下载-百度离线宝 安卓版v1.0.0.0-PC6安卓网
- 【云原生 | Kubernetes 系列】1个POD2个container实现Wordpress K8s部署
- 【建议收藏】新到手的电脑Windows10/11系统优化、使用规范和技巧及软件推荐,提升范电脑性能和体验
- 最全收集整理GitHub上受欢迎的Android UI Library
- 基于JAVA爱馨敬老院网站计算机毕业设计源码+系统+lw文档+部署
- python读取word详解【from docx import Document】
- macOS Ventura 13.0 (22A380) Boot ISO 原版可引导镜像
热门文章
- MSSQL_2017年4月最新全国手机号段手机归属地数据库360000条记录
- java 反斜杠数量_java学习过程所遇到反斜杠“\”都有哪些用法?
- Git基于分支重新创建一个新项目
- JVM知识体系学习七:了解JVM常用命令行参数、GC日志详解、调优三大方面(JVM规划和预调优、优化JVM环境、JVM运行出现的各种问题)、Arthas
- [图文教程]十分钟为游戏项目集成成就系统
- PVD可编程电压监测器
- wordpress最佳架构_大学的22个最佳WordPress主题
- C语言程序设计:将字符串的小写字母转换为大写字母
- 虚拟机启动以后卡在Probing EDD (edd off to disable) …. ok [closed]
- 【程序源代码】情侣小窝小程序