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.104
port: 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是否含有该key
return 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 { @Autowired
private SellerService sellerService; @Autowired
private StringRedisTemplate redisTemplate; @Autowired
private 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至redis
String 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. 清除cookie
CookieUtil.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 { @Autowired
private 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(); //查询cookie
Cookie 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 { @Autowired
private 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");
}
springboot项目:登录 登录aop拦截 使用Redis与cookie 进行设置获取清除操作的更多相关文章
- 在SpringBoot项目中添加SpringMVC拦截器
1.认识拦截器 SpringMVC的拦截器(Interceptor)不是Filer,同样可以实现请求的预处理.后处理.使用拦截器仅需要两个步骤 实现拦截器 注册拦截器 1.1实现拦截器 实现拦截器可以 ...
- SpringBoot项目中,AOP的使用
Springboot中自带依赖 1.创建一个SellerAuthorizeAspect类,打上标签@Aspect和@Component @Aspect @Component @Slf4j public ...
- SpringBoot项目中,异常拦截
SpringBoot自带异常拦截@ControllerAdvice 1.创建一个SellerExceptionHandler类打上@ControllerAdvice标签 @ControllerAdvi ...
- Redis——SpringBoot项目使用Lettuce和Jedis接入Redis集群
Jedis连接Redis: 非线程安全 如果是多线程环境下共用一个Jedis连接池,会产生线程安全问题,可以通过创建多个Jedis实例来解决,但是创建许多socket会影响性能,因此好一点的方法是使用 ...
- 用redis和cookie做单用户登录
因为公司的项目需要用到单用户登录,于是今天用redis和cookie给系统添加了单用户登录功能,再次简单记录一下. 单用户登录是为了防止同一账户在不同电脑和不同浏览器里面同时登录.所以我这边的思路是: ...
- springboot(五).如何在springboot项目中使用拦截器
在每个项目中,拦截器都是我们经常会去使用的东西,基本上任一一个项目都缺不了拦截器的使用. 如日志记录.登录验证,session验证等,都需要拦截器来拦截URL请求,那springboot中的拦截器是如 ...
- Springboot项目使用aop切面保存详细日志到ELK日志平台
上一篇讲过了将Springboot项目中logback日志插入到ELK日志平台,它只是个示例.这一篇来看一下实际使用中,我们应该怎样通过aop切面,拦截所有请求日志插入到ELK日志系统.同时,由于往往 ...
- springboot(12)Redis作为SpringBoot项目数据缓存
简介: 在项目中设计数据访问的时候往往都是采用直接访问数据库,采用数据库连接池来实现,但是如果我们的项目访问量过大或者访问过于频繁,将会对我们的数据库带来很大的压力.为了解决这个问题从而redis数据 ...
- 拦截器的作用之session认证登录和资源拦截
背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到springboot默认的文件夹中得文件.另外,经常需要判断当前 ...
随机推荐
- linux每天一小步---awk命令详解
1 命令功能 awk是linux环境下的一个强大的文本工具,由于awk天生提供对文件中文本分列进行处理,所以如果一个文件中的每行都被特定的分隔符(默认为空格)隔开,我们就可以将这个文件看成是有很多列的 ...
- IntelliJ IDEA 2016.1.3(64) license server 与汉化
license server:http://idea.iteblog.com/key.php 汉化:将resources_cn.jar 复制到安装IDEA安装目录下的lib文件夹中.重新打开即可. r ...
- 23 DesignPatterns学习笔记:C++语言实现 --- 2.6 Facade
23 DesignPatterns学习笔记:C++语言实现 --- 2.6 Facade 2016-07-22 (www.cnblogs.com/icmzn) 模式理解
- 23 DesignPatterns学习笔记:C++语言实现 --- 1.4 Builder
23 DesignPatterns学习笔记:C++语言实现 --- 1.4 Builder 2016-07-21 (www.cnblogs.com/icmzn) 模式理解
- tomcat mac
在mac上安装tomcat,教程很不错:http://blog.csdn.net/j2ee_me/article/details/7928493 注意 1.要下载二进制文件,core, 2.解压后移动 ...
- How do I determine if I'm being run under the debugger?
#include <assert.h>#include <stdbool.h>#include <sys/types.h>#include <unistd.h ...
- 咏南中间件增加HTTPS.SYS支持
咏南中间件增加HTTPS.SYS支持 老客户可免费升级. HTTPS.SYS可以开发强大而稳定的REST SERVER. 微软在Windows Vista (server 2008) 以后使用http ...
- ------------------java collection 集合学习 ----小白学习笔记,,有错,请指出谢谢
<!doctype html>java对象集合学习记录 figure:first-child { margin-top: -20px; } #write ol, #write ul { p ...
- Linux下source文件两种方法
1.直接source命令加文件 source /etc/rc.d/init.d/functions 2.点(.)加文件 . /etc/rc.d/init.d/functions
- 配置git使用socks5代理
git config --global http.proxy 'socks5://127.0.0.1:1080' git config --global https.proxy 'socks5://1 ...