Spring MVC REST 컨트롤러에서 HTTP 헤더 정보에 액세스하려면 어떻게 해야 합니까?
저는 웹 프로그래밍, 특히 Java에 익숙하지 않기 때문에 헤더와 본문이 무엇인지 알게 되었습니다.
봄 MVC를 이용한 RESTful 서비스를 쓰고 있습니다.를 사용하여 간단한 서비스를 생성할 수 있습니다.@RequestMapping
내 컨트롤러에 있습니다.REST 서비스 컨트롤러에서 내 메서드에 도달하는 요청에서 HTTP 헤더 정보를 얻는 방법을 이해하는 데 도움이 필요합니다.헤더를 해석하여 몇 가지 속성을 얻고 싶습니다.
어떻게 하면 그 정보를 얻을 수 있는지 설명해 주시겠습니까?
매개 변수에 주석을 다는 경우@RequestHeader
파라미터는 헤더 정보를 가져옵니다.다음과 같이 할 수 있습니다.
@RequestHeader("Accept")
을 손에 넣다Accept
header를 클릭합니다.
이 매뉴얼에서는 다음과 같이 기술합니다.
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
}
그Accept-Encoding
그리고.Keep-Alive
헤더 값은 에 기재되어 있습니다.encoding
그리고.keepAlive
파라미터를 지정합니다.
그리고 걱정하지 마세요.우리는 모두 무언가에 집착한다.
를 사용할 수 있습니다.@RequestHeader
로의 주석.HttpHeaders
method 매개 변수를 사용하여 모든 요청 헤더에 액세스할 수 있습니다.
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
예를 들어 user="test"와 같은 헤더 파라미터의 솔루션은 다음과 같습니다.
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
System.out.println(headers.get("user"));
}
HttpEntity를 사용하여 본문과 헤더를 모두 읽을 수 있습니다.
@RequestMapping(value = "/restURL")
public String serveRest(HttpEntity<String> httpEntity){
MultiValueMap<String, String> headers =
httpEntity.getHeaders();
Iterator<Map.Entry<String, List<String>>> s =
headers.entrySet().iterator();
while(s.hasNext()) {
Map.Entry<String, List<String>> obj = s.next();
String key = obj.getKey();
List<String> value = obj.getValue();
}
String body = httpEntity.getBody();
}
언급URL : https://stackoverflow.com/questions/19556039/how-to-get-access-to-http-header-information-in-spring-mvc-rest-controller
'sourcecode' 카테고리의 다른 글
TypeScript 정적 클래스 (0) | 2023.02.15 |
---|---|
2개의 JSON 객체 비교 (0) | 2023.02.15 |
C#을 사용하여 csv 파일을 json으로 변환 (0) | 2023.02.15 |
워드프레스:$wpdb->get_results를 사용할 때 결과를 이스케이프 해제하려면 어떻게 해야 합니까? (0) | 2023.02.15 |
선택한 ng-option이 변경될 때 값 가져오기 (0) | 2023.02.15 |