SpringVC 拦截器+自定义注解 实现权限拦截

1.springmvc配置文件中配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd 
	http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven />  

	<!-- 将 springSwaggerConfig加载到spring容器 -->
   	<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />
	<!-- 将自定义的swagger配置类加载到spring容器 -->
 	<bean class="com.aisino.qysds.common.util.SwaggerConfig" />
 	<!-- 静态资源文件,不会被Spring MVC拦截 -->
	<mvc:resources mapping="/api-doc/**" location="/api-doc/" />
	<mvc:resources mapping="/js/**" location="/js/" />
	<!-- 自动扫描的包名 -->  
    <context:component-scan base-package="com.controller"/>

	<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
 			   <value>text/html;charset=UTF-8</value>
			   <value>text/plain;charset=UTF-8</value>
			   <!-- <value>application/x-www-form-urlencoded;charset=UTF-8</value> -->				
			</list>
		</property>
	</bean>
	
	<mvc:interceptors>
		
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="AuthorityAnnotationInterceptor"/>
        </mvc:interceptor>
	</mvc:interceptors>	
	<aop:aspectj-autoproxy />
	
</beans>

  2.自定义拦截器,实现HandlerInterceptor接口或继承HandlerInterceptor

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {

    final Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings("unchecked")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //开启swagger时,打开
//        if (handler instanceof ResourceHttpRequestHandler) {
//            logger.error("swagger ok");
//            return true;
//        }
        Authority authority=null;
        HandlerMethod handler2=(HandlerMethod) handler;
        Class<?> clazz=handler2.getBeanType();
        //类注解
        if(clazz.isAnnotationPresent(Authority.class)){
            authority=clazz.getAnnotation(Authority.class);
        }
        //方法注解
        if(handler2.getMethodAnnotation(Authority.class)!=null){
            authority = handler2.getMethodAnnotation(Authority.class);
        }
        if(null == authority){
            //没有声明权限,放行
            return true;
        }
                
        logger.debug("fireAuthority", authority.toString());
        HttpSession session = request.getSession();
        boolean aflag = false;
        
        for(AuthorityType at : authority.authorityTypes()){
            List<String> role = (List<String>)session.getAttribute("用户权限");
            if(role.contains(at.getId())){
                aflag = true;
                if(aflag){
                    aflag = true;
                    break;
                }
            }
        }
        if(false == aflag){
            response.getWriter().println("没有权限");
        }
        return aflag;
    }
    
}

3.自定义权限注解

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//支持在类和方法上
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authority {
    AuthorityType[] authorityTypes();
}

4.权限枚举

public enum AuthorityType{

    ONE("一级", "1"), 
    TWO("二级", "2"), 
    THREE("三级", "3"),
    ;
    private String name;
    private String id;

    private AuthorityType(String name, String id) {
        this.name = name;
        this.id = id;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

5.控制器Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/test/allow")
@Authority(authorityTypes =AuthorityType.ONE)
public class TestController extends BaseController {

    @ResponseBody
    @RequestMapping(value = "test", method = RequestMethod.GET)
    @Authority(authorityTypes =AuthorityType.TWO)
    public boolean test() {
        return true;
    }

}

 每次请求有权限的接口,都需要验证当前用户是否有该权限,有则通过,反之不通过,最后附上springmvc执行流程

 

posted @ 2018-03-13 16:46  紫薇帝星的故事  阅读(637)  评论(0编辑  收藏  举报