登录、登出:

第一步:在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. 解决CentOS7虚拟机无法上网并设置CentOS7虚拟机使用静态IP上网

    最近在VMware虚拟机里玩Centos,装好后发现上不了网.经过一番艰辛的折腾,终于找到出解决问题的方法了.最终的效果是无论是ping内网IP还是ping外网ip,都能正常ping通.方法四步走: ...

  2. 基于微软XAML技术的前端开发方法

    使用XAML技术的平台目前包括WPF,Silverlight,Windows8等平台,未来的Windows10统一Windows App也使用XAML技术. 前端开发指通过可视化集成开发环境进行用户界 ...

  3. 用pillow和 opencv做透明通道的两图混全(blend)

    from PIL import Image as image foreground = image.open("donkey.png") background = image.op ...

  4. django drf 权限permission

    https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions from django.shortcut ...

  5. .net core 2.0 mvc 初步学习

    mvc_study *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !impor ...

  6. 关于StreamReader.ReadToEnd方法

    以前写抓取网页的代码喜欢用ReadToEnd,因为简单省事,后来发现,在爬取网页的时候,如果网速很慢,ReadToEnd超时的几率很大.使用Read改写后,超时几率大大减小,完整代码如下: /// & ...

  7. WP8.1StoreApp(WP8.1RT)---发送邮件和短信

    在WP7/8中,发送短信是利用了EmailComposeTask和SmsComposeTask来实现的. 在WP8.1 Store App中,原来的方式已经失效,采用了新的方法:ChatMessage ...

  8. 当我们在谈论multidex65535时,我们在谈论什么

    本文来自网易云社区 作者:郑文 首先我们并不在讨论车牌号.本文尽量避免谈论重复的技术点,只探讨一下multidex提供给我们的技术启示. 原理 multidex技术原理可以分成两个部分: 在app启动 ...

  9. 码农的福利来了, 编程在线Androd 客户端上线了

    编程在线下载: 编程在线网站:http://codestudy.sinaapp.com (最新版2.1) 编程在线移动版:http://codestudy.sinaapp.com/mobile/ 编程 ...

  10. 销售系统项目业务分析和Java中使用邮箱

    项目一般大致可分为三个模块, 我们以销售系统为例 分为 基础模块 进货模块 财务模块三个 基础模块分为:权限模块 产品模块和基础代码,基础模块的设计十分重要会影响到整个项目, 代码较为简单 核心模块 ...