我想创建REST服务器,它接受XML请求和从Ruby代码到不同控制器的纯文本。我试图实现这一点:
@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 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 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
我使用:
<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")
在WildFly上作为WAR应用程序部署时,Sun.Reflect包中包含的Spring Boot应用程序可能需要一些高级JDK反射API来进行代理。为此,您的应用程序需要在其manifest.mf文件中将jdk.unsupported作为依赖项列出(请参见WildFly wiki)。
源码-所以我首先应用了这个。
<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>
接下来,我修复了日志记录:我将这里接受的答案的第一个注释应用于日志记录,并从这里向src/main/resources添加了一个基本的logback.xml。
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<exclude-subsystems>
<subsystem name="logging" />
</exclude-subsystems>
</deployment>
</jboss-deployment-structure>
<?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注册到您的内容类型来完成。
在您的情况下,由于请求正文中有querystring,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);
}
编辑: XML请求示例: XML响应示例:
当我尝试对输入进行限制时,我在java中遇到了很多麻烦。在此示例中,我需要字符串代码仅接受和等符号。我如何检查以确保没有数字、字母或其他符号?谢谢
红线位于“打开导航抽屉”和“关闭导航抽屉”下 这张图片显示了这个问题
如果你使用过python,你会发现字符串和int/float/double便捷的拼接方式;但如果你使用C++,可能你每次需要的时候搜索一下才能知道。本文提供两种简单的方式来完成这个功能。 std::to_string() 通过std::to_string()将数字类型转换成std::string类型,从而可以直接使用+完成字符串的拼接。 # include <iostream> int main
主要内容:实例,实例,实例,转义字符,字符编码,字符串内建方法,实例,字符串 unpack 指令Ruby 中的 String 对象用于存储或操作一个或多个字节的序列。 Ruby 字符串分为单引号字符串(')和双引号字符串("),区别在于双引号字符串能够支持更多的转义字符。 单引号字符串 最简单的字符串是单引号字符串,即在单引号内存放字符串: '这是一个 Ruby 程序的字符串' 如果您需要在单引号字符串内使用单引号字符,那么需要在单引号字符串使用反斜杠(\),这样 Ruby 解释器就不会认为