拦截器实例

package com.wanda.gmp.admin.web.interceptor;

import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wanda.common.util.CollectionUtils;
import com.wanda.gmp.admin.dao.model.auth.Menu;
import com.wanda.gmp.admin.service.auth.RoleService;
import com.wanda.gmp.admin.vo.auth.AdminUserInfo;
import com.wanda.gmp.admin.web.common.AuthException;
import com.wanda.gmp.admin.web.constants.Constants;
import com.wanda.gmp.admin.web.util.MenuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wanda.common.util.StringUtils;
import com.wanda.gmp.admin.web.annotation.LoginRequired;
import com.wanda.gmp.admin.web.util.WebUtils;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class WebInterceptor implements HandlerInterceptor {

    @Autowired
    private RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        AdminUserInfo adminUserInfo = WebUtils.getCurrentUserInfo();
        if (handler != null && handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method != null) {
                LoginRequired loginRequired = handlerMethod.getBeanType().getAnnotation(LoginRequired.class);
                if (loginRequired == null) {
                    loginRequired = method.getAnnotation(LoginRequired.class);
                }
                if (loginRequired != null &&  adminUserInfo == null) {
                    response.sendRedirect(request.getContextPath() + "/?retUrl=" + URLEncoder.encode(request.getRequestURI() + (StringUtils.isNotEmpty(request.getQueryString()) ? request.getQueryString() : ""), "utf-8"));
                }
            }
            if(adminUserInfo!=null){
                WebUtils.setUserInfo(adminUserInfo);
            }
            
        }
//        return true;
        if(null == adminUserInfo || Constants.ADMIN_USER.equals(adminUserInfo.getWanxin())){
            request.setAttribute("tagid", "A");
            return true;
        }
        List<Menu>  menuList = adminUserInfo.getMenuList(); //当前用户下的菜单权限

        //获得url
        String query = request.getQueryString();
        String url = request.getRequestURI().replace(request.getContextPath(), "")
                + ((query != null && query.length() > 0) ? ("?" + query) : "");

        //查找二级菜单下的所有操作;将tagid按都好分隔拼成字符串放到request里
        String tagides = findOptionTagid(url,menuList);
        if(StringUtils.isNotBlank(tagides)) {
            if(tagides.endsWith(",")) tagides = tagides.substring(0,tagides.length()-1);
            request.setAttribute("tagid", tagides);
        }
        if(checkExistMenu(url)){ //只有菜单表里存在的菜单才做拦截;其他不做拦截
            if (checkRight(url, menuList)) {
                return true;
            } else {
                log.error("您没有权限访问[{}]",url);
                throw new AuthException("权限控制");
            }
        }else{
            return true;
        }
    }

    /**
     * 前台控制菜单模块树级别最多三级;1,2级为菜单;3级为菜单下的操作;
     * @param url
     * @param menuList
     * @return
     */
    private String findOptionTagid(String url,List<Menu>  menuList){
        StringBuffer returnValue = new StringBuffer();
        PathMatcher matcher = new AntPathMatcher();
        Menu currentMenu = null;
        String u = url;
        if(u.indexOf("?") > 0) u = url.substring(0,url.indexOf("?"));
        for(Menu menu:menuList){
            if(StringUtils.isNotBlank(menu.getUri()) && matcher.match(menu.getUri(),u)){
                currentMenu = menu;
                break;
            }
        }
        if(currentMenu != null){
            String menuid = null;
            if(Constants.MENU_TYPE_1.equals(currentMenu.getType().toString())){ //菜单
                menuid = currentMenu.getId().toString();
            }else{
                menuid = currentMenu.getParentId().toString();
            }
            if(StringUtils.isNotBlank(menuid)){
                for(Menu menu : menuList){
                    if(menu.getParentId().toString().equals(menuid) && StringUtils.isNotBlank(menu.getTagid())){ //菜单下所有操作
                        returnValue.append(menu.getTagid()).append(",");
                    }
                }
            }
        }

        return returnValue.toString();
    }

    /**
     * 校验菜单是否存在
     * @param url
     * @return
     */
    private boolean checkExistMenu(String url) {
        boolean existMenu = false;
        String u = url;
        if(u.indexOf("?") > 0) u = url.substring(0,url.indexOf("?"));
//        List<Menu> menuList = WebUtils.getMenuResource();
        List<Menu> menuList = MenuUtils.initMenuUtils().getMenuList();
        if(menuList == null || menuList.size() <= 0){
            menuList = roleService.findMenu();
            MenuUtils.initMenuUtils().setMenuList(menuList);
        }
        if(CollectionUtils.isEmpty(menuList)){
            return existMenu;
        }

        PathMatcher matcher = new AntPathMatcher();
        for(Menu menu:menuList){
            if(StringUtils.isNotBlank(menu.getUri()) && matcher.match(menu.getUri(),u)){
                existMenu = true;
                break;
            }
        }
        return existMenu;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        if (StringUtils.isEmpty(request.getRequestedSessionId())) {
            try {
                request.getSession(true);
            } catch (Throwable e) {
                
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if (ex != null) {
            ex.printStackTrace();
            log.error("", ex);
        }
    }

    /**
     * 权限检查
     * @param url
     * @param menuList
     * @return
     */
    public boolean checkRight(String url, List<Menu> menuList) {
        boolean hasRight = false;
        String u = url;
        if(u.indexOf("?") > 0) u = url.substring(0,url.indexOf("?"));
        if(CollectionUtils.isEmpty(menuList)){
            return true;
        }
        PathMatcher matcher = new AntPathMatcher();

        for (Menu menu : menuList) {
            if (matcher.match(menu.getUri(),u)) {
                hasRight = true;
                break;
            }
        }
        return hasRight;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值