Как вернуть ответ xml или json на основе расширения URLJAVA

Программисты JAVA общаются здесь
Anonymous
Как вернуть ответ xml или json на основе расширения URL

Сообщение Anonymous »

У меня есть служба Java, построенная на jaxrs, и она возвращает ответ на основе расширения URL-адреса.
Например: http://localhost:8080/employees по умолчанию возвращает xml, http://localhost :8080/employees.json возвращает данные json.
Итак, существует множество сервисов и пользовательского интерфейса, использующих этот сервис Jaxrs, теперь я конвертирую этот сервис из jaxrs, Springbased restservice, как я могу реплицировать то же самое с restcontroller на основе пружины?
Если я передам Accept: application/json или application/xml, он работает нормально, но я ищу решение для расширения URL.
Я пробовал 1) WebMvcConfigurer 2) перехватчики/фильтры, но ничего не работает
1) WebMvcConfigurer

Код: Выделить всё

package com.example.spring_rest_to_graphql;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true)
.favorParameter(false)
.ignoreAcceptHeader(true)
.useRegisteredExtensionsOnly(true)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("json", MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML);
}
}
2) перехватчики/фильтры[/b]

Код: Выделить всё

package com.example.spring_rest_to_graphql;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class ContentNegotiationInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
if (requestURI.endsWith(".json")) {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
} else if (requestURI.endsWith(".xml")) {
response.setContentType(MediaType.APPLICATION_XML_VALUE);
}
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// No implementation needed
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// No implementation needed
}
}
Итак, после всех этих изменений, когда я нажимаю на эту конечную точку http://localhost:8080/employes, я получаю ответ в формате XML, но когда я нажимаю на эту конечную точку http:/ /localhost:8080/employees.json Я получаю страницу с ошибкой 404.

Подробнее здесь: https://stackoverflow.com/questions/787 ... -extension

Вернуться в «JAVA»