복붙노트

[SPRING] 여러 시나리오 @RequestMapping은 Accept 또는 ResponseEntity와 함께 JSON / XML을 생성합니다.

SPRING

여러 시나리오 @RequestMapping은 Accept 또는 ResponseEntity와 함께 JSON / XML을 생성합니다.

나는 Spring 4.0.7과 함께 일하고있다.

연구 목적으로 Spring MVC에 관해서, 나는 다음과 같은 것들을 가지고있다 :

@RequestMapping(value="/getjsonperson", 
                method=RequestMethod.GET, 
                produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Person getJSONPerson(){
    logger.info("getJSONPerson - getjsonperson");
    return PersonFactory.createPerson();
}

@RequestMapping(value="/getperson.json", method=RequestMethod.GET)
public @ResponseBody Person getPersonJSON(){
    logger.info("getPerson - getpersonJSON");
    return PersonFactory.createPerson();
}

각각은 잘 작동하며 JSON과 확장자가있는 경우와없는 경우를 모두 관찰합니다.

XML과 동일합니다.

@RequestMapping(value="/getxmlperson",
                method=RequestMethod.GET,
                produces=MediaType.APPLICATION_XML_VALUE
                )
public @ResponseBody Person getXMLPerson(){
    logger.info("getXMLPerson - getxmlperson");
    return PersonFactory.createPerson();
}

@RequestMapping(value="/getperson.xml", method=RequestMethod.GET)
@ResponseBody
public Person getPersonXML(){
    logger.info("getPerson - getpersonXML");
    return PersonFactory.createPerson();
}

각각은 잘 작동하며, 확장을 포함하여 확장하거나 확장하지 않고 XML을 모두 준수합니다.

이제는 안절부절하고 있습니다. 나는 다음과 같은 것을 가지고 있습니다.

@RequestMapping(value="/person/{id}/", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE, 
                          MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<Person> getPersonCustomizedRestrict(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return new ResponseEntity<>(person, HttpStatus.FOUND);//302     
}

MediaType을 관찰하십시오, JSON과 XML의 경우 혼합되어 있습니다.

RestTemplate을 통해 Accept 값을 나타낼 수 있습니다.

    if(type.equals("JSON")){
        logger.info("JSON");
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    }
    else if(type.equals("XML")){
        logger.info("XML");
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    }
    ….

    ResponseEntity<Person> response =
                restTemplate.exchange("http://localhost:8080/spring-utility/person/{id}/customizedrestrict",
                                      HttpMethod.GET,
                                      new HttpEntity<Person>(headers),  
                                      Person.class,
                                       id
                                     ); 

따라서 지금까지 하나의 URL / URI를 사용하여 XML 또는 JSON 형식으로 일부 데이터를 가져올 수있었습니다. 잘 작동합니다.

내 문제는 봄 MVC와 함께 ... 그냥 고려

@RequestMapping(value="/{id}/person", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE,  
                          MediaType.APPLICATION_XML_VALUE})
public @ResponseBody Person getPerson(@PathVariable Integer id){
    return personMapRepository.findPerson(id);
}

다음을 통해 해당 처리기 메서드 (@RequestMapping)를 호출하거나 활성화 할 수 있습니다.

질문 1 :

그러나 일반적인 연결을 위해? 수락 값을 어떻게 설정할 수 있습니까? 가능하니?

나는이 문제를 해결하기 위해 다른 방법으로 생각했다.

관찰하십시오 :

따라서

@RequestMapping(value="/getpersonformat", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE,  
                          MediaType.APPLICATION_XML_VALUE})
public @ResponseBody Person getPerson(@RequestParam String format){
    return personMapRepository.findPerson(id);
}

질문 2 :

반환 형식 형식을 사용자 지정하려면 위에 표시된 메서드의 코드를 추가해야합니다? JSON 또는 XML이 가능합니까?

나는 다음과 같이 생각했다.

@RequestMapping(value="/getpersonformataltern",
        method=RequestMethod.GET
        produces={MediaType.APPLICATION_JSON_VALUE, 
                  MediaType.APPLICATION_XML_VALUE}
        )
public ResponseEntity<Person> getPersonFormat(@RequestParam String format){
    logger.info("getPersonFormat - format: {}", format);
    HttpHeaders httpHeaders = new HttpHeaders();
    if(format.equals("json")){
        logger.info("Ok JSON");
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    }
    else{
        logger.info("Ok XML");
        httpHeaders.setContentType(MediaType.APPLICATION_XML);
    }
    return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
}

그러나:

URL을 실행하면 :

나는 얻다

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <id>1</id>
    <firstName>Manuel</firstName>
    <lastName>Jordan</lastName>
…
</person>

예, XML!

참고 : 콘솔에서 Ok JSON을 인쇄하는지 확인할 수 있습니다.

URL을 실행하면 :

나는 얻다

This XML file does not appear to have any style information associated with it. 
The document tree is shown below.

<person>
    <id>1</id>
    <firstName>Manuel</firstName>
    <lastName>Jordan</lastName> 
    …
</person>

질문 3

JSON 출력을 수정하려면 위에 표시된 메소드의 코드를 추가해야합니다. 나는 무엇이 잘못되었거나 실종되었는지 알지 못한다.

세 가지 질문이 있습니다.

고맙습니다

알파

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    Map<String,MediaType> mediaTypes = new LinkedHashMap<>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON);
    mediaTypes.put("xml", MediaType.APPLICATION_XML);
    configurer.mediaTypes(mediaTypes);
    configurer.defaultContentType(MediaType.TEXT_HTML);
}

해결법

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

    1.수락 헤더를 사용하면 REST 서비스에서 json 또는 xml 형식을 얻는 것이 정말 쉽습니다.

    수락 헤더를 사용하면 REST 서비스에서 json 또는 xml 형식을 얻는 것이 정말 쉽습니다.

    이것은 내 컨트롤러입니다.

    @RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
        public UIProperty getProperties() {
            return uiProperty;
        }
    

    REST 서비스를 사용하려면 header가 MediaType.APPLICATION_JSON_VALUE 또는 MediaType.APPLICATION_XML_VALUE 일 수있는 아래 코드를 사용할 수 있습니다.

    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", header);
    
    HttpEntity entity = new HttpEntity(headers);
    
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
    return response.getBody();
    

    01 편집 :

    application / xml을 사용하려면이 종속성을 추가하십시오.

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
    
  2. ==============================

    2.모든 문제는 콘텐츠 형식 협상과 매개 변수 전달을 섞어 사용한다는 것입니다. 그것들은 다른 레벨에있는 것들입니다. 보다 구체적으로 말하면 질문 2에 대해 반환 할 미디어 유형으로 응답 헤더를 구성했습니다. 실제 내용 협상은 응답 헤더가 아닌 요청 헤더의 미디어 유형 승인을 기반으로합니다. 실행이 getPersonFormat 메소드의 구현에 도달하면 컨텐츠 협상이 완료되었는지 여부는 확실하지 않습니다. 구현에 따라 다릅니다. 그렇지 않다면, 당신은 원하는 것을 가지고 요청 헤더 수락 타입을 덮어 쓸 수있다.

    모든 문제는 콘텐츠 형식 협상과 매개 변수 전달을 섞어 사용한다는 것입니다. 그것들은 다른 레벨에있는 것들입니다. 보다 구체적으로 말하면 질문 2에 대해 반환 할 미디어 유형으로 응답 헤더를 구성했습니다. 실제 내용 협상은 응답 헤더가 아닌 요청 헤더의 미디어 유형 승인을 기반으로합니다. 실행이 getPersonFormat 메소드의 구현에 도달하면 컨텐츠 협상이 완료되었는지 여부는 확실하지 않습니다. 구현에 따라 다릅니다. 그렇지 않다면, 당신은 원하는 것을 가지고 요청 헤더 수락 타입을 덮어 쓸 수있다.

    새로운 ResponseEntity <> (PersonFactory.createPerson (), httpHeaders, HttpStatus.OK)를 반환하십시오.

  3. ==============================

    3.필자는 매개 변수 중심의 콘텐츠 유형에 params 필터를 사용하는 것을 선호했습니다. 이는 produce 특성과 함께 사용해야한다고 생각합니다.

    필자는 매개 변수 중심의 콘텐츠 유형에 params 필터를 사용하는 것을 선호했습니다. 이는 produce 특성과 함께 사용해야한다고 생각합니다.

    @GetMapping(value="/person/{id}/", 
                params="format=json",
                produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Person> getPerson(@PathVariable Integer id){
        Person person = personMapRepository.findPerson(id);
        return ResponseEntity.ok(person);
    } 
    @GetMapping(value="/person/{id}/", 
                params="format=xml",
                produces=MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
        return GetPerson(id); // delegate
    }
    
  4. from https://stackoverflow.com/questions/26676613/multiple-scenarios-requestmapping-produces-json-xml-together-with-accept-or-res by cc-by-sa and MIT license