복붙노트

[SPRING] @RequestMapping의 어떤 param이 호출되는지를 아는 법

SPRING

@RequestMapping의 어떤 param이 호출되는지를 아는 법

이것은 내 @RequestMapping 주석입니다.

  @RequestMapping({"/loginBadCredentials", "/loginUserDisabled", "/loginUserNumberExceeded"})
  public String errorLogin(...){        
            ... 
        }

메소드 errorLogin 내부에는 "url"이라는 세 URL 중 어느 것이 "알 수있는"방법이 있습니까?

해결법

  1. ==============================

    1.HttpServletRequest를 매개 변수로 추가하고이를 사용하여 현재 요청 경로를 찾습니다.

    HttpServletRequest를 매개 변수로 추가하고이를 사용하여 현재 요청 경로를 찾습니다.

    업데이트 : Spring은 또한 RequestContextHolder를 제공합니다 :

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    String currentReqUri = attributes.getRequest().getRequestURI();
    

    제 생각에는 첫 번째 접근법이 더 낫고 좀 더 테스트 가능합니다.

  2. ==============================

    2.HttpServletRequest를 메소드 매개 변수에 삽입 한 다음 호출 된 URI를 가져올 수 있습니다.

    HttpServletRequest를 메소드 매개 변수에 삽입 한 다음 호출 된 URI를 가져올 수 있습니다.

      @RequestMapping({"/loginBadCredentials", "/loginUserDisabled", "/loginUserNumberExceeded"})
      public String errorLogin(HttpServletRequest request) {        
                String uri = request.getRequestURI(); 
                // do sth with the uri here
      }
    
  3. ==============================

    3.가장 간단한 방법은 HttpServletRequest를 삽입하고 uri를 얻는 것입니다.

    가장 간단한 방법은 HttpServletRequest를 삽입하고 uri를 얻는 것입니다.

    @RequestMapping({"/loginBadCredentials", "/loginUserDisabled", "/loginUserNumberExceeded"})
    public String errorLogin(HttpServletRequest request) {        
            String uri = request.getRequestURI(); 
            // switch on uri what you need to do
    }
    
  4. from https://stackoverflow.com/questions/34919809/how-to-know-which-param-of-requestmapping-is-called by cc-by-sa and MIT license