0

我正在尝试设置一个http:inbound-gateway只接受 json 的。我的 xml 配置看起来像。

<int-http:inbound-gateway id="inboundGateway"
        supported-methods="POST"
        request-payload-type="eu.model.MyRequest"
        request-channel="inputChannel"
        mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS" 
        path="/myService"
        reply-timeout="50000"
        message-converters="converters"
        merge-with-default-converters="false"
        validator="myValidator">
         <int-http:request-mapping consumes="application/json"/>
    </int-http:inbound-gateway>
    
    <util:list id="converters">
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
    </util:list>

我已经看到,从 5.2 版本开始,验证器可用于在发送到通道之前检查有效负载,但我似乎找不到示例。添加validator="myValidator"似乎验证了 myRequest。

但是,尽管<int-http:request-mapping consumes="application/json"/>将内容限制为有效的 json 并且 Validator 发出HTTP Status 400 – Bad Request 错误是在 html 中返回的?

如何覆盖它以返回自定义 json 响应?

编辑 1 这是我的完整 xml 配置

<int-http:inbound-gateway id="inboundGateway"
        supported-methods="POST"
        request-payload-type="eu.neurocom.wind.msdp.cis.model.MyRequest"
        request-channel="inputChannel"
        reply-channel="responseChannel"
        error-channel="errorChannel"
        mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS" 
        path="/myservice"
        reply-timeout="50000"
        message-converters="converters"
        merge-with-default-converters="false"
        validator="myValidator">
         <int-http:request-mapping consumes="application/json" produces="application/json" />
    </int-http:inbound-gateway>
    
    <util:list id="converters">
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
    </util:list>
    
    <int:service-activator
            input-channel="errorChannel"
            output-channel="responseChannel"
            ref="globalExceptionHandler"
            method="handleError"
    />  
    <int:service-activator ref="incomingActivator" input-channel="inputChannel" output-channel="responseChannel" method="handle"></int:service-activator>

我的端点激活器方法看起来像

public Message<MyResponse> handle(Message<MyRequest> message) {
logger.info("Received {}", message);
...}

如果在激活器中引发错误,则错误通道将返回我的自定义 json 响应,否则甚至在记录我在 text/html 中的响应下方得到的消息之前;。

<body>
<h1>HTTP Status 400 – Bad Request</h1>
<hr class="line" />
<p><b>Type</b> Status Report</p>
<p><b>Message</b> Validation failure</p>
<p><b>Description</b> The server cannot or will not process the request due to something that is perceived to be a
    client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
</p>
<hr class="line" />
<h3>Apache Tomcat/8.5.58</h3>

编辑 2 Bellow 是我的验证器类,调用了 looger,如果不存在 msidsn 则触发

public class MyRequestValidator implements Validator {

    private static final Logger logger = LoggerFactory.getLogger(MyRequestValidator.class);

    @Override
    public boolean supports(Class<?> clazz) {
        return CisRequest.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        logger.debug("validatorCalled");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "msisdn", "msisdn.required");
    }

}

我的web.xml

    <servlet>
        <servlet-name>inboundGateway</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>\WEB-INF\classes\spring-integration-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <!-- Note: All <servlet> elements MUST be grouped together and
        placed IN FRONT of the <servlet-mapping> elements -->

    <servlet-mapping>
        <servlet-name>inboundGateway</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
4

1 回答 1

0

该组件中的逻辑是这样的:

    message = prepareRequestMessage(servletRequest, httpEntity, headers, payload);
        }
        catch (Exception ex) {
            MessageConversionException conversionException =
                    new MessageConversionException("Cannot create request message", ex);
            MessageChannel errorChannel = getErrorChannel();
            if (errorChannel != null) {
                ErrorMessage errorMessage = buildErrorMessage(null, conversionException);
                if (expectReply) {
                    return this.messagingTemplate.sendAndReceive(errorChannel, errorMessage);
                }
                else {
                    this.messagingTemplate.send(errorChannel, errorMessage);
                    return null;
                }
            }
            else {
                throw conversionException;
            }
        }

因此,如果您为 配置了一个error-channel<int-http:inbound-gateway>您可以根据需要处理抛出IntegrationWebExchangeBindException并生成自定义回复。

注意:我们可能需要在文档中提及这种方法。目前它只指向处理验证错误的标准 Spring MVC 方法:https ://docs.spring.io/spring-integration/docs/5.3.2.RELEASE/reference/html/http.html#http-validation 。随意提出一个GH问题!

于 2020-10-05T13:11:47.650 回答