引入依赖:
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
cmd到redis的bin目录下执行redis-server redis.windows.conf
controller类
@Controller
@RequestMapping("/manager")
public class ManagerController {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private ManagerService managerService;
//使用cookie需要传入HttpServletResponse response
@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response) {
//1.与数据库里的数据匹配
Manager manager=managerService.findManagerByUsernameAndPassword(username,password);
if(manager==null){
return "login/login";
}
//2,设置token到redis
String token= UUID.randomUUID().toString();
//设定redis过期时间
Integer expire= RedisConstant.EXPIRE;
//format格式化一下,希望token按照固定的模式
redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),username,expire, TimeUnit.SECONDS);
//redisTemplate.opsForValue().set("abc","bdcancjasnc");
//3,设置token到cookie
CookieUtil.set(response, CookieConstant.TOKEN,token,expire);
return "redirect:/users/user/list";
}
@GetMapping("/log")
public String logout(HttpServletRequest request, HttpServletResponse response, Map<String,Object>map) {
//将cookie和token删掉
//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(直接将时间设置为0)
CookieUtil.set(response,CookieConstant.TOKEN,null,0);
}
return "login/login";
}
}
RedisConstant.java
public interface RedisConstant {
String TOKEN_PREFIX="token_%s";//储存的key以token_开头的
Integer EXPIRE=7200;//两小时
}
CookieUtil.java
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.setPath("/");//路径是指http://127.0.0.1:8080这个路径下的网页cookie有效
cookie.setMaxAge(maxAge);//过期时间
response.addCookie(cookie);
}
/**
* 获取cookie
* @param request
* @param name
* @return
*/
public static Cookie get(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = readCookieMap(request);
//判断cookie中是否包含name
if (cookieMap.containsKey(name)) {
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();
if (cookies != null) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
}
aop的配置类
@Slf4j
@Aspect
@Component
public class ManagerAuthorizeAspect {
@Autowired
private StringRedisTemplate redisTemplate;
// @Pointcut("execution(public * com.wangzhou.controller.Manager*.*(..))"+"&& !execution(public * com.wangzhou.controller.ManagerController.*(..))")
//可以排除同名的
@Pointcut("execution(public * com.wangzhou.controller.UserController.*(..))")
public void verify() {
}
@Before("verify()")
public void doVerify() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
System.out.println("request" + request.getContextPath());
//查询cookie
Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
if (cookie == null) {
log.warn("【登录校验】Cookie中查不到token");
throw new ManagerAuthorizeException();
}
//去redis里查
String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
if (StringUtils.isEmpty(tokenValue)) {
log.warn("【登录校验】Redis中查不到token");
throw new ManagerAuthorizeException();
}
}
@Before("execution(public * com.wangzhou.controller.ManagerController.*(..))")
public void doVer() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
System.out.println("request" + request.getContextPath());
//查询cookie
Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
// String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
if (cookie== null) {
}else {
log.warn("【用户已登录过】,无需填写账号密码");
throw new LoginAuthorizeException();
}
}
}
成功后若是未通过登录界面进行用户密码登录,而是直接访问主界面,会自动返回登录界面
Original url: Access
Created at: 2019-06-24 12:32:43
Category: default
Tags: none
未标明原创文章均为采集,版权归作者所有,转载无需和我联系,请注明原出处,南摩阿彌陀佛,知识,不只知道,要得到
最新评论