首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在spring集成中验证传入的json http入站适配器并返回Json响应

如何在spring集成中验证传入的json http入站适配器并返回Json响应
EN

Stack Overflow用户
提问于 2020-10-05 09:31:08
回答 1查看 369关注 0票数 0

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

代码语言:javascript
复制
<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可以用于在发送到通道之前检查有效负载,但是我似乎找不到一个例子。添加validator="myValidator"似乎可以验证myRequest。

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

这如何被覆盖以返回自定义的json响应?

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

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
public Message<MyResponse> handle(Message<MyRequest> message) {
logger.info("Received {}", message);
...}

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

代码语言:javascript
复制
<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贝娄是我的验证器类,调用looger,如果msidsn不存在触发器

代码语言:javascript
复制
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

代码语言:javascript
复制
    <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-05 13:11:47

该组件中的逻辑如下:

代码语言:javascript
复制
    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,并根据您的意愿生成一个自定义回复。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64205975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档