登录、登出:

第一步:在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 进行设置获取清除操作的更多相关文章

  1. 在SpringBoot项目中添加SpringMVC拦截器

    1.认识拦截器 SpringMVC的拦截器(Interceptor)不是Filer,同样可以实现请求的预处理.后处理.使用拦截器仅需要两个步骤 实现拦截器 注册拦截器 1.1实现拦截器 实现拦截器可以 ...

  2. SpringBoot项目中,AOP的使用

    Springboot中自带依赖 1.创建一个SellerAuthorizeAspect类,打上标签@Aspect和@Component @Aspect @Component @Slf4j public ...

  3. SpringBoot项目中,异常拦截

    SpringBoot自带异常拦截@ControllerAdvice 1.创建一个SellerExceptionHandler类打上@ControllerAdvice标签 @ControllerAdvi ...

  4. Redis——SpringBoot项目使用Lettuce和Jedis接入Redis集群

    Jedis连接Redis: 非线程安全 如果是多线程环境下共用一个Jedis连接池,会产生线程安全问题,可以通过创建多个Jedis实例来解决,但是创建许多socket会影响性能,因此好一点的方法是使用 ...

  5. 用redis和cookie做单用户登录

    因为公司的项目需要用到单用户登录,于是今天用redis和cookie给系统添加了单用户登录功能,再次简单记录一下. 单用户登录是为了防止同一账户在不同电脑和不同浏览器里面同时登录.所以我这边的思路是: ...

  6. springboot(五).如何在springboot项目中使用拦截器

    在每个项目中,拦截器都是我们经常会去使用的东西,基本上任一一个项目都缺不了拦截器的使用. 如日志记录.登录验证,session验证等,都需要拦截器来拦截URL请求,那springboot中的拦截器是如 ...

  7. Springboot项目使用aop切面保存详细日志到ELK日志平台

    上一篇讲过了将Springboot项目中logback日志插入到ELK日志平台,它只是个示例.这一篇来看一下实际使用中,我们应该怎样通过aop切面,拦截所有请求日志插入到ELK日志系统.同时,由于往往 ...

  8. springboot(12)Redis作为SpringBoot项目数据缓存

    简介: 在项目中设计数据访问的时候往往都是采用直接访问数据库,采用数据库连接池来实现,但是如果我们的项目访问量过大或者访问过于频繁,将会对我们的数据库带来很大的压力.为了解决这个问题从而redis数据 ...

  9. 拦截器的作用之session认证登录和资源拦截

    背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到springboot默认的文件夹中得文件.另外,经常需要判断当前 ...

随机推荐

  1. mongodb-win32-i386-3.0.6 使用

    一.下载地址 https://fastdl.mongodb.org/win32/mongodb-win32-i386-3.0.6.zip 二.安装 1. systeminfo OS 名称: Micro ...

  2. MarkDown语法练习笔记

    MarkDown使用规则 标题Markdown 支持两种标题的语法,类 Setext 和类 atx 形式 Setext 形式:用底线的形式 Selext形式采用: 1.最高阶标题(=)2.第二阶标题( ...

  3. UIWebView清除缓存和cookie[转]

    现在项目遇到一个问题,游戏底层用Cocos2d-x,公告UI实现是用的UIWebView, 然后第一次在有网络的环境下运行公告UI,会加载url链接,同时就会自动存入缓存,当下次手机没有网络的环境下, ...

  4. 超详细JSON解析步骤

    JSON简介 JAVAScript Object Notation是一种轻量级的数据交换格式 具有良好的可读和便于快速编写的特性. 业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了 ...

  5. Codeforces766B Mahmoud and a Triangle 2017-02-21 13:47 113人阅读 评论(0) 收藏

    B. Mahmoud and a Triangle time limit per test 2 seconds memory limit per test 256 megabytes input st ...

  6. 使用Object.create()实现继承

    一.常见继承方式 我们日常开发中常见的继承方式主要有: 1.默认模式: Child.prototype = new Parent(); 2.借用构造函数: function Child(a, b, c ...

  7. [Erlang21]Erlang性能分析工具eprof fporf的应用

    前段时间项目改代码突然cpu波动很大,排查了好久都没有找到原因,只能求助于性能测试工具 :   <<Erlang程序设计>>----Joe Armstorng[哈哈,登月第一人 ...

  8. 手动编译安装lamp之php

    转自马哥教育讲课文档 三.编译安装php-5.4.8 1.解决依赖关系: 请配置好yum源(可以是本地系统光盘)后执行如下命令: # yum -y groupinstall "X Softw ...

  9. Java--下载历史版本登录账户

    目前在官网下载低于jdk1.8的java jdk的时候需要登陆,这边分享一个账号,方便下载 2696671285@qq.com 密码:Oracle123 转自-- jdk下载以前版本需要的账号(转) ...

  10. 1416: Kick Ass Biu [几何]

    点击打开链接 1416: Kick Ass Biu [几何] 时间限制: 1 Sec 内存限制: 128 MB 提交: 174 解决: 35 统计 题目描述 在玩Kick Ass的时候,可以发现子弹的 ...