我想创建一个REST Server,它接受来自Ruby代码的XML请求和纯文本到不同的控制器中。我试图实现这一点:
@SpringBootApplication
public class Application extends SpringBootServletInitializer implements WebMvcConfigurer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
..............
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.removeIf(converter -> converter instanceof MappingJackson2XmlHttpMessageConverter);
converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
converters.add(new MappingJackson2XmlHttpMessageConverter(
((XmlMapper) createObjectMapper(Jackson2ObjectMapperBuilder.xml()))
.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)));
converters.add(new MappingJackson2HttpMessageConverter(createObjectMapper(Jackson2ObjectMapperBuilder.json())));
}
private ObjectMapper createObjectMapper(Jackson2ObjectMapperBuilder builder) {
builder.indentOutput(true);
builder.modules(new JaxbAnnotationModule());
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.defaultUseWrapper(false);
return builder.build();
}
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//MyRequestBodyHttpMessageConverter converter = new MyRequestBodyHttpMessageConverter();
FormHttpMessageConverter converter = new FormHttpMessageConverter();
//MediaType utf8FormEncoded = new MediaType("application","x-www-form-urlencoded", Charset.forName("UTF-8"));
//MediaType mediaType = MediaType.APPLICATION_FORM_URLENCODED; maybe UTF-8 is not needed
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
//converter.setSupportedMediaTypes(Arrays.asList(utf8FormEncoded));
converters.add(converter);
MappingJackson2HttpMessageConverter conv1 = new MappingJackson2HttpMessageConverter();
conv1.getObjectMapper().registerModule(new JaxbAnnotationModule());
converters.add(conv1);
MappingJackson2XmlHttpMessageConverter conv = new MappingJackson2XmlHttpMessageConverter();
// required by jaxb annotations
conv.getObjectMapper().registerModule(new JaxbAnnotationModule());
converters.add(conv);
}
}
检查XML的正确格式:
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
PaymentTransaction response;
if (ex.getMessage().contains("Required request body")) {
response = new PaymentTransaction(PaymentTransaction.Response.failed_response, 350,
"Invalid XML message: No XML data received", "XML request parsing failed!");
} else {
response = new PaymentTransaction(PaymentTransaction.Response.failed_response, 351,
"Invalid XML message format", null);
}
return ResponseEntity.badRequest().body(response);
}
}
控制器类:
@RestController()
public class HomeController {
@Autowired
public HomeController(Map<String, MessageProcessor> processors, Map<String, ReconcileProcessor> reconcileProcessors,
@Qualifier("defaultProcessor") MessageProcessor defaultProcessor,
AuthenticationService authenticationService, ClientRepository repository,
@Value("${request.limit}") int requestLimit) {
// Here I receive XML
}
@GetMapping(value = "/v1/*")
public String message() {
return "REST server";
}
@PostMapping(value = "/v1/{token}", consumes = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public PaymentResponse handleMessage(@PathVariable("token") String token,
@RequestBody PaymentTransaction transaction, HttpServletRequest request) throws Exception {
// Here I receive XML
}
@PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(@RequestBody Map<String, String> keyValuePairs) {
// Here I receive key and value in request body
}
@PostMapping(value = "/v1/summary/by_date/{token}", consumes = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public PaymentResponses handleReconcile(@PathVariable("token") String token, @RequestBody Reconcile reconcile,
HttpServletRequest request) throws Exception {
// Here I receive XML
}
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public static class UnauthorizedException extends RuntimeException {
UnauthorizedException(String message) {
super(message);
}
}
}
如您所见,在某些方法中,我收到XML,而在其他方法中,我收到key=value&.....
形式的String
我如何配置Spring接受两种类型? 还应该将Rest控制器拆分为其他文件吗?
编辑:
示例XML请求:
<?xml version="1.0" encoding="UTF-8"?>
<payment_transaction>
<transaction_type>authorize</transaction_type>
<transaction_id>2aeke4geaclv7ml80</transaction_id>
<amount>1000</amount>
<currency>USD</currency>
<card_number>22</card_number>
<shipping_address>
<first_name>Name</first_name>
</shipping_address>
</payment_transaction>
示例XML响应:
<?xml version="1.0" encoding="UTF-8"?>
<payment_response>
<transaction_type>authorize</transaction_type>
<status>approved</status>
<unique_id>5f7edd36689f03324f3ef531beacfaae</unique_id>
<transaction_id>asdsdlddea4sdaasdsdsa4dadasda</transaction_id>
<code>500</code>
<amount>101</amount>
<currency>EUR</currency>
</payment_response>
样品通知请求:
uniqueid=23434&type=sale&status=33
样本通知响应:它应该仅返回HTTP状态OK。
我使用:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath />
</parent>
Java版本:“ 10.0.2” 2018-07-17 和Wildfly 13。
关于我使用的XML生成:
@XmlRootElement(name = "payment_transaction")
public class PaymentTransaction {
public enum Response {
failed_response, successful_response
}
@XmlElement(name = "transaction_type")
public String transactionType;
@XmlElement(name = "transaction_id")
public String transactionId;
@XmlElement(name = "usage")
答案 0 :(得分:0)
当在WildFly上作为WAR应用程序部署时,Spring Boot 应用程序可能需要一些高级JDK反射API才能 代理,包含在sun.reflect软件包中。为此,您的 应用程序需要将jdk.unsupported列为其依赖项 MANIFEST.MF文件(有关此信息,请参阅WildFly Wiki)。
source-所以我首先应用了这个。
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<packagingExcludes>WEB-INF/web.xml</packagingExcludes>
<archive>
<manifestEntries>
<Dependencies>jdk.unsupported</Dependencies>
</manifestEntries>
</archive>
</configuration>
</plugin>
接下来,我修复了日志记录:我应用了the first comment of the accepted answer here进行日志记录,并将basic logback.xml从此处添加到src / main / resources。
所以我的基本jboss-deployment-structure.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<exclude-subsystems>
<subsystem name="logging" />
</exclude-subsystems>
</deployment>
</jboss-deployment-structure>
从现在开始,在Wildfly控制台中,您可以查看发生的情况。
我以两种分布测试了POC:
仅Servlet分发 (wildfly-servlet-13.0.0.Final.zip)
这与基本的jboss-deployment-structure.xml一起使用。
应用服务器分发 (wildfly-13.0.0.Final.zip)
在此服务器上,我必须添加org.reactivestreams模块:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<exclude-subsystems>
<subsystem name="logging" />
</exclude-subsystems>
<dependencies>
<module name="org.reactivestreams"/>
</dependencies>
</deployment>
</jboss-deployment-structure>
您必须将此文件放入src / main / webapp / WEB-INF目录。
如果您需要使用与application / x-www-form-urlencoded不同的支持内容类型,则可以通过将适当的MessageConverter注册为您的内容类型来实现。
在您的情况下,由于请求正文中的查询字符串,FormHttpMessageConverter将是“适当的”,并且您必须将内容类型指定为MY_OTHER_CONTENT_TYPE常量:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FormHttpMessageConverter converter = new FormHttpMessageConverter();
MediaType utf8FormEncoded = new MediaType("application","x-www-form-urlencoded", Charset.forName("UTF-8"));
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED, MY_OTHER_CONTENT_TYPE));
converters.add(converter);
super.configureMessageConverters(converters);
}
但是用过的转换器应该能够处理它,所以您必须检查转换器的源(我这样做了,如果是FormHttpMessageConverter,它应该以这种方式工作)我认为(或者您可以尝试一下) ,并且如果可以,则可以)。有时候simple并非如此,但是我希望对您来说它将以这种方式工作。
如果您无法解决,请给我们一个有问题的请求的完整示例,我将尝试使其正常工作。
进行测试
请确保使用POST方法使用Content-Type:application / x-www-form-urlencoded标头,并且您的参数正在请求正文中传输。 (我曾使用Boomerang Chrome插件进行测试,并在其中为发布请求定义了请求参数时,将其作为获取参数添加到了请求URL中。这显然导致了错误的结果。)
希望这些对您有所帮助。如果没有,请在应用正确的日志记录设置后向我们显示原因(请更新您的帖子,例外)。