본문 바로가기
Spring

Spring 4 interceptor custom annotation

by 수앙 2019. 11. 13.

Spring 4.3 기준으로

Controller 클래스에서 빈과 메소드 단위 custom annotation 설정을

인터셉터에서 체크하는 방법에 대해 알아본다.

 

1. Custom annotation 생성

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.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorization {

	enum Role {
		ADMIN, USER
	}

	Role[] name();

}

 

2. Controller에 custom annotation 설정

샘플 용도이기 때문에 빈과 메소드에 custom annotation 모두 설정

@Controller
@Authorization(name = { Role.ADMIN, Role.USER })
public class SampleController {

	@GetMapping(value = "/sample/list")
	@Authorization(name = { Role.ADMIN, Role.USER })
	public String list(ModelMap model) {
		return "sample/list";
	}
    
	@GetMapping(value = "/sample/form")
	@Authorization(name = Role.ADMIN)
	public String form(ModelMap model) {
		return "sample/form";
	}

}

 

3. Interceptor에서 custom annotation 체크

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

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod method = (HandlerMethod) handler;
        
		// 메소드 권한부터 체크
		Authorization authorization = method.getMethodAnnotation(Authorization.class);

		if (authorization == null) {
			// 메소드 권한이 없으면 빈에서 권한 체크
			authorization = method.getBean().getClass().getAnnotation(Authorization.class);
		}

		if (authorization != null) {
			// 권한 체크
		} else {
			// 권한 체크 안함
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}

 

끝.

'Spring' 카테고리의 다른 글

Spring boot p6spy 적용  (1) 2021.01.07
Spring batch chunk 동작 방식  (0) 2020.11.05
Spring 4 request logging  (0) 2019.11.07
Spring 4.3 Redis Sentinel Pubsub 설정  (0) 2018.06.16
Spring 4.3 Redis Sentinel 연동  (0) 2018.06.16

댓글