登录、登出:
第一步:在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"); }