스프링 부트 컨트롤러 콘텐츠 네고시에이션
Spring-boot 어플리케이션에는 단순한 REST 컨트롤러가 기술되어 있습니다만, 요청 헤더의 Content-Type 파라미터에 근거해 JSON 또는 XML을 반환하기 위한 콘텐츠네고시에이션을 실장하는 방법을 잘 모르겠습니다.누가 설명 좀 해줄래? 내가 뭘 잘못하고 있는 거야?
컨트롤러 방식:
@RequestMapping(value = "/message", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public Message getMessageXML(@RequestParam("text") String text) throws Exception {
Message message = new Message();
message.setDate(new Date());
message.setName("Test");
message.setAge(99);
message.setMessage(text);
return message;
}
이 메서드를 호출할 때는 항상 JSON이 표시됩니다(이 메서드를 지정해도).Content-Type되려고application/xml또는text/xml).
매핑과 콘텐츠유형이 다른2개의 메서드를 각각 실장하면 xml에서XML을 취득할 수 있지만, 1개의 메서드로2개의 mediaType을 지정하면 동작하지 않습니다(다음의 예와 같습니다).
제가 원하는 것은 그 전화입니다\message엔드포인트 및 수신
- GET 요청의 Content-Type이 application/xml로 설정되어 있는 경우 XML
- Content-Type이 어플리케이션/json일 경우 JSON
어떤 도움이라도 감사합니다.
편집: 모든 미디어 유형을 허용하도록 컨트롤러를 업데이트했습니다.
@RequestMapping(value = "/message", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = MediaType.ALL_VALUE)
public Message getMessageXML(@RequestParam("text") String text) throws Exception {
Message message = new Message();
message.setDate(new Date());
message.setName("Vladimir");
message.setAge(35);
message.setMessage(text);
return message;
}
ContentNegotiationConfigr를 사용할 수 있습니다.
먼저, 이 명령어를 덮어씁니다.configureContentNegotiationmethod를 지정합니다.
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).
favorParameter(true).
defaultContentType(MediaType.APPLICATION_JSON).
mediaType("xml", MediaType.APPLICATION_XML);
}
}
favorParameter(true)- 파라미터 또는 Accept 헤더보다 경로 식을 선호합니다.
defaultContentType(MediaType.APPLICATION_JSON)- 기본 콘텐츠유형을 설정합니다.즉, 경로 식을 통과하지 못하면 스프링이 응답으로 JSON을 생성합니다.
mediaType("xml", MediaType.APPLICATION_XML)- XML 경로 표현 키를 설정합니다.
컨트롤러가 다음과 같이 선언된 경우:
@Controller
class AccountController {
@RequestMapping(value="/accounts", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody List<Account> list(Model model, Principal principal) {
return accountManager.getAccounts(principal) );
}
}
이렇게 부르면localhost:8080/app/accounts.jsonSpring은 응답으로 JSON을 생성합니다.그래서 당신이 전화하면localhost:8080/app/accounts.xmlXML 응답을 수신합니다.
자세한 내용은 여기를 참조하십시오.
블로그 투고 @RequestMapping with Products and Consumes에서 몇 가지 힌트를 찾을 수 있습니다.
Content-Type 헤더와 Accept 헤더에 관한 항에 주의해 주십시오.
@RequestMapping과 생산 및 소비:헤더 Content-Type 및 Accept를 사용하여 요청 내용과 응답에 필요한 MIME 메시지를 확인할 수 있습니다.알기 쉽게 하기 위해 @RequestMapping은 어떤 메서드가 호출될지 및 응답 콘텐츠유형을 지정할 수 있는 변수를 생성하고 소비합니다.예를 들어 다음과 같습니다.
@RequestMapping(value="/method6", produces={"application/json","application/xml"}, consumes="text/html") @ResponseBody public String method6(){ return "method6"; }위의 메서드는 Content-Type을 text/html로만 사용할 수 있으며 application/json 및 application/xml 유형의 메시지를 생성할 수 있습니다.
이 다른 접근법(ResponseEntity 객체 사용)을 사용하여 착신 메시지유형을 검출하여 대응하는 메시지를 생성할 수도 있습니다(@ResponseBody 주석도 이용).
2.확장 Spring Boot 2.6 등)./resource.xml콘텐츠 네고시에이션에서는 권장되지 않기 때문에 향후 새로운 어플리케이션에서 콘텐츠네고시에이션에 의존하는 것은 증거가 되지 않을 수 있습니다. 스트래티지 " " )/resource?format=xml 있는 것 도 디폴트로 디세블로 되어 있는 것 같습니다.포맷 파라미터 전략을 이노블로 만들려면 컨피규레이션클래스를 추가합니다.
@Configuration
@EnableWebMvc
public class WebConfig
implements WebMvcConfigurer
{
@Override
public void configureContentNegotiation( ContentNegotiationConfigurer configurer )
{
configurer
.favorParameter( true );
}
}
Java 8 이후 8은WebMvcConfigurer 없이 수 있습니다.WebMvcConfigurerAdapter.
언급URL : https://stackoverflow.com/questions/33009918/spring-boot-controller-content-negotiation
'programing' 카테고리의 다른 글
| 각도 오류: "ngModel은 'input'의 기존 속성이 아니므로 바인딩할 수 없습니다." (0) | 2023.04.04 |
|---|---|
| 리액트 스위칭 다이내믹세그먼트가 액세스하면 크래시 (0) | 2023.04.04 |
| fs.writeFileSync를 사용하여 JSON 개체를 JSON 파일에 쓰는 중 (0) | 2023.04.04 |
| Oracle에서 테이블 크기를 확인하는 방법 (0) | 2023.04.04 |
| App() vs 클래스 App은 App.js 파일에서 컴포넌트를 확장합니다. (0) | 2023.04.04 |