1. 程式人生 > >SpringVC 攔截器+自定義註解 實現權限攔截

SpringVC 攔截器+自定義註解 實現權限攔截

json.js 加載 bean media tar attr esp 權限 encoding

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執行流程

技術分享圖片

SpringVC 攔截器+自定義註解 實現權限攔截