Spring MVC로 작업중 입려된 파라미터 검증이 필요하면 공통 성질을 뽑아 aspect로 작업해도 괜찮을 듯 싶다. 공통 성질로는 파라미터 타입, 사이즈, 널체크 등이 있겠지만.. 우선은 널 체크만 작업해보자.


1. @annotation 생성

- 입력값이 필수인 필드명을 array로 받는 단순한 annotation을 생성하자.


사용예) 

@HPNullCheck(parameters={"name", "id", "password"})

public ModelAndView DEMO01(HttpServletRequest request, HttpServletResponse response) {

    ...............

}


@annotation 클래스)

import java.lang.annotation.ElementType;


import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface HPNullCheck {


String[] parameters();

}


2. @annotation 구현 클래스

- Reflection 기능을 사용하여 @annotation 클래스 기능(널 체크)을 구현한다.


RequestFacade 처리)

- 요청 객체가 RequestFacade 이면 아래와 같이 처리한다.

public void requestFacadeNullCheck(RequestFacade request) throws BizException {

Method[] methods = delcaringClass.getMethods();

for(Method method : methods) {

if(method.getName().equals(methodName)) {

HPNullCheck hpNullCheck = (HPNullCheck) method.getAnnotation(HPNullCheck.class);

if(hpNullCheck != null) {

String[] parameters = hpNullCheck.parameters();        

                        if(parameters == null) return;

     

                        for(int i = 0;i<parameters.length;i++) {

                          if(!parameters[i].equals("")) {

                  String value = request.getParameter(parameters[i]);        

                                    

                                    if(StringUtils.isEmpty(value)) {

                                        throw new BizException("ERO001", "["+parameters[i]+"] 값을 확인하세요.");

                                    }

                                }

    }

}

}

}

}


MultipartHttpServletRequest 처리)

- 요쳥 객체가 DefaultMultipartHttpServletRequest 이면 아래와 같이 처리한다.

public void defaultMultipartHttpServletRequestNullCheck(MultipartHttpServletRequest request) throws BizException {

Method[] methods = delcaringClass.getMethods();

for(Method method : methods) {

HPNullCheck hpNullCheck = (HPNullCheck) method.getAnnotation(HPNullCheck.class);

if(hpNullCheck != null) {

String[] parameters = hpNullCheck.parameters();        

if(parameters == null) return;

for(int i = 0;i<parameters.length;i++) {

if(!parameters[i].equals("")) {

String value = request.getParameter(parameters[i]);        

if(StringUtils.isEmpty(value)) {

throw new BizException("ERO001", "["+parameters[i]+"] 값을 확인하세요.");

}

}

}

}

}

}


Aspect로 Controller 클래스의 메소드를 @Around로 걸고 요청객체의 타입에 따라 위와 같이 Reflect를 활용하여 처리한다.


Posted by 짱가쟁이