欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Mvc拦截器的实现与登录案例

程序员文章站 2022-04-15 19:16:58
Spring Mvc拦截器拦截器的基本配置简单案例实现拦截器的基本配置1.自定义拦截器实现HandlerInterceptor 接口public class PermissionInterceptor implements HandlerInterceptor {private final static Log log= LogFactory.getLog(PermissionInterceptor.class);@Overridepublic boolean preHandle(Http...

拦截器的基本配置

1.自定义拦截器实现HandlerInterceptor 接口

public class PermissionInterceptor implements HandlerInterceptor {
	private final static Log log= LogFactory.getLog(PermissionInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("preHandle");
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		log.info("postHandle");
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		log.info("afterCompletion");
	}
}

2.配置spring mvc文件

/** 所有路径及里面的子路径

/* 当前路径下的所有路径,不含子文件

/  项目根目录的请求
  <mvc:interceptors>
    <!-- 拦截所有 -->
    <mvc:interceptor>
        <!-- 拦截指定的请求url -->
        <mvc:mapping path="/user/**"/>
        <bean class="cn.ybzy.common.interceptor.Permissioninterceptor"/>
    </mvc:interceptor>
    </mvc:interceptors>

3.编写登录方法

   @RequestMapping(value = "login",method = RequestMethod.GET)
    @ResponseBody
    public String login(String name,String pwd){
        System.out.println("name:"+name+"------"+"pwd:"+pwd);
        return "Hello World!";
    }

4.断点验证
Spring Mvc拦截器的实现与登录案例
Spring Mvc拦截器的实现与登录案例
5.拦截器执行流程
preHandle在请求之前调用
Spring Mvc拦截器的实现与登录案例
执行业务
Spring Mvc拦截器的实现与登录案例
postHandle在请求后调用
Spring Mvc拦截器的实现与登录案例
afterCompletion在请求结束调用
Spring Mvc拦截器的实现与登录案例

简单案例实现

1.用户登录过程实现

    @RequestMapping(value = "login",method = RequestMethod.GET)
    @ResponseBody
    public String login(String username, String password, HttpSession session, ServletResponse response){
        //向浏览器写入cookies
        Cookie ck = new Cookie("sso-cookies",session.getId());
        ck.setDomain("localhost");
        ck.setPath("/");
        ck.setHttpOnly(true);
        ck.setMaxAge(60 * 30);
        HttpServletResponse resp=(HttpServletResponse)response;
        resp.addCookie(ck);
    
    	//构造一个成功登录的用户信息
        JSONObject object = new JSONObject();
        object.put("name",username);
        object.put("pwd",password);
    
        //向redis写入数据
        Jedis jedis = new Jedis("localhost");
        jedis.setex(session.getId(),60*30,object.toJSONString());
        return "Hello World!";
    }

2.拦截业务实现

@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("preHandle");
		//请求Controller中的方法名
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		
		//请求的方法名
		String methodName = handlerMethod.getMethod().getName();
		//请求方法所在类的类名
		String className = handlerMethod.getBean().getClass().getSimpleName();
		
		//解析请求参数
		HashMap<Object, Object> hashMap = new HashMap<>();
		Map paramMap = request.getParameterMap();
		Iterator it = paramMap.entrySet().iterator();
		while (it.hasNext()){
			Map.Entry entry = (Map.Entry)it.next();
			String mapKey = (String)entry.getKey();
			
			String mapValue = StringUtils.EMPTY;
			
			// entry.getValue()里面的value返回的是一个String[]
			Object obj = entry.getValue();
			if(obj instanceof String[]){
				String[] strs = (String[])obj;
				mapValue = Arrays.toString(strs);
			}
			hashMap.put(mapKey,mapValue);
		}
		log.info("request parameters : {}",hashMap);
		
		if(StringUtils.equals(className,"UserController") && StringUtils.equals(methodName,"login")){
			log.info("权限拦截器拦截到请求,className:{},methodName:{}",className,methodName);
			return true;
		}
		
		log.info("权限拦截器拦截到请求,className:{},methodName:{},param:{}",className,methodName, hashMap.toString());
		
		
		User user = null;
		
		//获取登录时写入的cookies
		String loginToken=null;
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie cookie : cookies){
				if(StringUtils.equals(cookie.getName(),"sso-cookies")){
					loginToken= cookie.getValue();
				}
			}
		}
		
		//从redis中取登录的用户信息
		if(StringUtils.isNotEmpty(loginToken)){
			Jedis jedis = new Jedis("localhost");
			String userJson = jedis.get(loginToken);
			user =JSONObject.parseObject(userJson,User.class);
		}
		
		//假设该登录用户的角色 admin
		String userRole="admin";
		
		if(user == null || (!StringUtils.equals(userRole, "admin"))){
			// 设置编码/返回值类型
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");
			
			PrintWriter out = response.getWriter();

			if(user == null){
				out.print("拦截器拦截,未登录!");
			}else{
				out.print("拦截器拦截,无权限!");
			}
			out.flush();
			out.close();
			
			//返回false.不执行controller里的方法
			return false;
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		log.info("postHandle");
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		log.info("afterCompletion");
	}
}

3.访问登录方法

1.request参数的map,里面的value返回的是一个String[]

Spring Mvc拦截器的实现与登录案例

2.cookies写入浏览器

Spring Mvc拦截器的实现与登录案例

3.用户信息存入redis

Spring Mvc拦截器的实现与登录案例
4.获取登录用户信息:

   @RequestMapping(value = "getUserInfo",method = RequestMethod.GET)
    @ResponseBody
    public String getUserInfo(String username, String password, HttpServletRequest request){
    //获取cookie
        String loginToken=null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(StringUtils.equals(cookie.getName(),"sso-cookies")){
                    loginToken= cookie.getValue();
                }
            }
        }
        
        //redis中取用户信息
        if(StringUtils.isNotEmpty(loginToken)){
            Jedis jedis = new Jedis("localhost");
            String userJson = jedis.get(loginToken);
            return  JSONObject.parseObject(userJson).toJSONString();
        }
        return null;
    }
1.已登录且String userRole="admin";

Spring Mvc拦截器的实现与登录案例

2.未登录

Spring Mvc拦截器的实现与登录案例

3.已登录且String userRole="product";

Spring Mvc拦截器的实现与登录案例

本文地址:https://blog.csdn.net/qq_38628046/article/details/107348884

相关标签: Spring