【问题标题】:JSON reponse with Spring Controllers in Jetty vs TomcatJetty vs Tomcat 中带有 Spring 控制器的 JSON 响应
【发布时间】:2014-08-19 03:03:05
【问题描述】:

我正在构建一个简单的 Spring MVC webapp,并在 jetty 上进行开发。我的控制器绑定使用了这个:

@RequestMapping(value = RESTRoutes.CREATE_DOC, method = RequestMethod.POST)
    public  @ResponseBody String getDoc

并且从 JSONObject 返回一个字符串在我的 ajax 响应中正确解析为 JSON。

但是使用这些相同的控制器,我将我的 gradle war 部署到 tomcat 并且我的 json 以真正的字符串形式返回。

所以我改变了我的标题以使用 Map,这似乎修复了码头和 tomcat 中的问题:

@RequestMapping(value = RESTRoutes.CREATE_DOC, method = RequestMethod.POST)
        public  @ResponseBody Map<String, String> getDoc

我用这个将字符串转换为地图:

        HashMap<String, String> jsonResponse = new HashMap<String, String>();
        if(claimFolder.has("error")){
            response.setStatus(500);
        }else{
            jsonResponse = new ObjectMapper().readValue(claimFolder.toString(), HashMap.class);
        }
        return jsonResponse;

我的问题是为什么这是必要的?

这是我的杰克逊转换器配置:

<bean id="formConverter" class="org.springframework.http.converter.FormHttpMessageConverter" />

<!-- add byte[] converter -->
<bean id="byteArrayConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
   <property name="supportedMediaTypes" value="application/octet-stream" />
</bean>  

<!--  add in our JSON message converter -->
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json;charset=UTF-8" />
</bean>

<!-- add in our plain string message converter -->
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
    <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>

<!-- Expose the authenticated handler to all beans that have been declared via annotation -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>

TL;DR:为什么 jetty 和 tomcat 返回字符串化 JSON 的方式不同?

【问题讨论】:

    标签: json spring tomcat spring-mvc jetty


    【解决方案1】:

    嗯,Spring 内容协商将 String 对象转换为简单字符串而不将其编组为 JSON 对象是绝对正常的。为了在 JSON 对象中序列化 java String 对象,您需要预先将其包装在一些 java 类中。例如:

    QuestionStatus {
    
    private String status;
    
    public QuestionStatus(String status) {
    this.status = status;
    }
    
    public getStatus() {
    return status;
    }
    }
    

    因此,您必须在 Controller 方法中返回不是字符串而是 QuestionStatus。

    【讨论】:

    • 谢谢!我最终在所有端点上使用了 Map 对象,它似乎在 Jetty 和 Tomcat 上都能正常工作。你说得对,我可能应该创建一个 POJO 来代表我期望从数据库得到的响应。
    • 春天有时并不明显,但感谢它拥有广泛的社区 =)
    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2015-12-17
    相关资源
    最近更新 更多