1.权限控制
说明:如果用户不登录,则不允许访问购物车列表页面,如果没有登录则应该重定向到用户登录页面。
业务需求:当用户进行敏感操作时,必须要求用户先登录之后才可以访问后端服务器. 例如京东商城…
使用技术:
1.AOP
2.拦截器 :拦截用户的请求
2.拦截器
2.1SpringMVC调用原理图
2.2SpringMVC拦截器工作原理
2.3拦截器工作原理
3.编辑拦截器配置MvcConfigurer
package com.jt.config;
import com.jt.interceptor.UserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfigurer implements WebMvcConfigurer{
//开启匹配后缀型配置
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
//骗搜索引擎
configurer.setUseSuffixPatternMatch(true);
}
//配置拦截器策略
@Autowired
private UserInterceptor userInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userInterceptor)
.addPathPatterns("/cart/**","/order/**");
}
}
4.编辑拦截器UserInterceptor
1.如果用户没有登录想要访问购物车,则通过拦截器跳转到登录页面:
package com.jt.interceptor;
import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import com.jt.util.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class UserInterceptor implements HandlerInterceptor {
@Autowired
private JedisCluster jedisCluster;
/**
* 参数介绍:
* @param1 request 用户请求对象
* @param2 response 服务器响应对象
* @param3 handler 当前处理器本身
* @return Boolean true 请求放行 false 请求拦截 一般配合重定向使用
* @throws Exception
* 如果用户不登录则重定向到登录页面
*
* 需求: 1.检查cookie信息 2.检查Redis中是否有记录.
* true : 请求应该放行
* false: 请求应该拦截 则配合重定向的语法实现页面跳转到登录页面 使得程序流转起来
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String ticket = null;
//1.判断cookie中是否有记录
Cookie[] cookies = request.getCookies();
if(cookies !=null && cookies.length>0){
for (Cookie cookie : cookies){
if("JT_TICKET".equals(cookie.getName())){
ticket = cookie.getValue();
break;
}
}
}
//2.判断cookie数据是否有效
if(!StringUtils.isEmpty(ticket)){
if(jedisCluster.exists(ticket)){
String userJSON = jedisCluster.get(ticket);
User user = ObjectMapperUtil.toObject(userJSON, User.class);
//3.利用request对象进行数据的传递 request对象是最为常用的传递参数的媒介.
request.setAttribute("JT_USER", user);
return true; //表示用户已经登录.
}
}
//重定向到用户登录页面
response.sendRedirect("/user/login.html");
return false;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//销毁数据
request.removeAttribute("JT_USER");
}
}