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默认的文件夹中得文件.另外,经常需要判断当前 ...
随机推荐
- Hadoop学习【一】单机版搭建
首先要说一下,Hadoop 2.x版本以后的改动,在这里帖一篇文章,觉得写的不错. http://www.ibm.com/developerworks/cn/opensource/os-cn-hado ...
- NLog日志框架简写用法
本文转载:http://www.blogjava.net/qiyadeng/archive/2013/02/27/395799.html 在.net中也有非常多的日志工具,今天介绍下NLog.NLog ...
- Ubuntu命令基础
Ubuntu命令基础 1.打开终端窗口快捷键. Ctrl+alt+t 2.更新设置root密码. $sudo passwd root 3.切换到root用户用su,前提是自己设置了root密码(看 ...
- Scala程序编译运行
1.编译 Scala演示代码如下: <pre name="code" class="plain">/** * @author Administrat ...
- HTML5 Canvas之猜数字游戏
主要的内容描述的是如何渲染一个矩形的边框和填充背景,以及文字. 代码中有详细的注释: 效果图: 以下是代码: <!DOCTYPE html> <html lang="cn& ...
- 咏南中间件当作WEB SERVER使用方法
咏南中间件当作WEB SERVER使用方法 1)开启咏南中间件 2)浏览器打开http://localhost:5566/web?page=echo.html
- [Erlang33]使用recon从网页查看Erlang运行状态
0.需求分析 Erlang最好的卖点之一就是提供了一个非常强大的shell来查看Node运行时的各种状态,可以进行各种各样的内部查看,在运行时调试和分析,热更新代码. 但是总有一些在生产环境下要慎 ...
- VUE 学习笔记 一 指令
1.声明式渲染 v-bind 特性被称为指令.指令带有前缀 v-,以表示它们是 Vue 提供的特殊特性 <div id='app'> <span v-bind:title=" ...
- eayui js动态加载Datagrid,自适应宽度,高度
HTML: <div class="easyui-layout" style="min-height:100%;min-width:100%;"> ...
- ce+od无法同时附加进程的问题
CE+OD无法附加游戏进程的破解方法 来吧 别在为这烦恼了 其实看过 windows 核心编程那本书的人都知道 计算机编程领域 那些所谓的游戏保护 真的只是为难菜鸟而已,对于大鸟基本不起作用. 游戏无 ...