Я хотел получить ответ от spring-mvc-controller в формате json или xml в зависимости от параметра - 'format' в URL-адресе .Я могу добиться этого, используя ContentNegotiation , как показано в приведенном ниже коде.
Единственная проблема заключается в том, что я даю недопустимое значение в параметре 'format' Яполучение сообщения об ошибке (HTTP-статус 406 - недопустимо).
Как установить для него значение json по умолчанию, даже если ввод недопустим.
Нижеэто конфигурация:
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class RespConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.favorPathExtension(false)
.favorParameter(true)
.parameterName("format")
.ignoreAcceptHeader(true)
.useJaf(false)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xm", MediaType.APPLICATION_JSON);
}
}
Ответ приведенной выше конфигурации следующий:
для URL http://localhost:8080/SpringApi?format=xml :: xml response (как настроено)
для URL http://localhost:8080/SpringApi?format=json :: json response (как настроено)
для url http://localhost:8080/SpringApi :: ответ json по умолчанию (как настроено)
для URL http://localhost:8080/SpringApi?format=abc :: (HTTP-статус 406 - неприемлемо).
![Screenshot the error in the browser :](https://i.stack.imgur.com/ZkquP.jpg)