2017-11-16 8 views
2

私はSpring MVCアプリケーションを持っており、現在のリクエストについてコントローラ内でRequestMappingInfoを取得するか、HttpServletRequestからリクエストをキャストする必要があります。私はそれを行うことができる方法はありますか?HttpServletRequestからRequestMappingInfoを取得するにはどうすればよいですか?

@GetMapping 
public void test(RequestMappingInfo requestMappingInfo, 
       Authentication auth) { 
    service.verify(requestMappingInfo, auth); 
} 

答えて

0

私は春の文書を読んでこれを見つけました。

@Nullable公共RequestMappingInfo getMatchingCondition(HttpServletRequestのリクエスト)をチェックしますが、この要求のマッピング情報のすべての 条件は、提供要求と一致する場合と は、現在の要求に合わせた条件 と潜在的に新しい要求のマッピング情報を返します。たとえば、返されたインスタンスの には、現在のリクエストと一致するURLパターンのサブセットが含まれています。 が最上位に一致するパターンでソートされています。指定さ

getMatchingCondition in interface RequestCondition<RequestMappingInfo> 

私はこのコードをしようとしなかった、あなたは確認することができますしてください?

試験:あなたのコントローラで

private 
@Autowired HttpServletRequest request; 

@GetMapping 
public void test(RequestMappingInfo requestMappingInfo, Authentication auth{ 
     assertEquals(requestMappingInfo, requestMappingInfo.getMatchingCondition(request)); 
} 
+0

それは素晴らしいですが、私はそれをどのように注入することができますか? –

+0

RequestMappingInfoにデフォルトのコンストラクタがありません:[org.springframework.web.servlet.mvc.method.RequestMappingInfo]のインスタンス化に失敗しました:デフォルトコンストラクタが見つかりません –

+0

正確なインターフェイスURLを取得する必要があります。/test/{a_id}/{b_id}/{c_id}となり、HttpServletRequestをresult/test/1/2/3と一緒に使用することはできません。リフレクションによって現在のメソッドの@RequestMapping URLをキャッチするフィルタを挿入するほうが簡単でしょうか? –

0

RequestMappingHandlerMappingであなたのアノテーション付きメソッドとautowireにHttpServletRequestを追加します。その後、getHandlerMapping()を使用して、現在のRequestMappingInfoに関する情報を取得できます。例えば

、以下のプリントすべてのパターンマッチのURL:

@Autowired 
private RequestMappingHandlerMapping handlerMapping; 

@GetMapping 
public void test(RequestMappingInfo requestMappingInfo, 
      Authentication auth, 
      HttpServletRequest request) { 

    handlerMapping.getHandlerMethods() 
      .forEach((requestMappingInfo, handlerMethod) 
        -> System.out.println(requestMappingInfo.getPatternsCondition().getMatchingCondition(request))); 

} 
関連する問題