6. Annotation

배고픈 징징이 ㅣ 2023. 2. 9. 10:53

1. 설명

이제 로그인이 필요한 페이지와 아닌 페이지를 관리하기위해 어노테이션을 만들어보자.

@isPublic 어노테이션은 boolean 값을 가지며 사용자들의 접근을 관리한다.

 

2. Create Custom Annotation

  • @Retend : Compiler가 Annotation을 다루는 방법 정의 (어느 시점까지 영향을 미치는지 정의)
    • RetentionPolicy.SOURCE : Compile 전까지만 유효
    • RetentionPolicy.CLASS : Compiler가 Class를 참조할 때까지 유효
    • RetentionPolicy.RUNTIME : Compile 이후 Runtime시기에도 JVM에 의해 참조 가능
  • @Target : Annotation을 적용할 위치
    • ElementType.PACKAGE
    • ElementType.TYPE
    • ElementType.ANNOTATION_TYPE
    • ElementType.CONSTRUCTOR
    • ElementType.FIELD
    • ElementType.LOCAL_VARIABLE
    • ElementType.METHOD
    • ElementType.PARAMETER
    • ElementType.TYPE_PARAMETER
    • ElementType.TYPE_USE
  • Annotation은 특수한 Interface로 구분하여 @Interface로 선언한다.
    @Interface는 자동으로 Annotation  클래스를 상속받고, 내부의 Method들은 abstract 키워드가 자동으로 붙는다.
    그로인해 @Interface는 extends 절을 가질 수 없다
    • 어노테이션 타입 선언은 제네릭일 수 없다.
    • 메소드는 매개변수를 가질 수 없다.
    • 메소드는 타입 매개변수를 가질 수 없다.
    • 메소드 선언은 throws절을 가질 수 없다.

 

Example Code

@Retention(RetentionPolicy.[Retention])
@Target(ElementType.[Element])
public @interface [Annotation Name] {
    [Type] [Annotation Name]() default [Value];
}

 

3. 실제 코드

Access.java

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Access {
    boolean isPublic() default false;
}

 

User.java

public class UserController {
    ...

    @Access(isPublic = true)
    public Object login(JObject json, HttpSession session) {
        ...
    }

    public void logout(HttpSession session) {
        ...
    }

    ...
}

 

FrontFilter.java

...

private boolean run(HttpServletRequest request, HttpServletResponse response, ControllerProfile profile, Object controller, Method method) throws IOException {
    boolean loginRequired = true;
    Access access = method.getAnnotation(Access.class);
    if (access != null && access.isPublic()) loginRequired = false;

    User user = null;
    if (loginRequired) {
        user = (User) request.getSession().getAttribute("user");
        // 유저를 찾지못했을때
        if (user == null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return true;
        }

        CallContext.setUser(user);
    }

    ...
}

...
반응형

'Java > - Pure Java Project' 카테고리의 다른 글

8. Query Generator  (0) 2023.02.16
7. LocalThread & Transaction ( Runnable )  (0) 2023.02.13
5. JNDI : DB Connect  (0) 2023.02.08
4. Router (Dynamic Import & Create Class)  (0) 2023.02.07
3. Filter > Controller, Css  (0) 2023.02.06