简体   繁体   English

Spring MVC返回JSONS和异常处理

[英]Spring MVC returning JSONS and exception Handling

I am using Spring MVC with Controllers, my question is how do I return a JSON response which is different from the @ResponseBody object which is returned and convereted to a JSON to be returned. 我正在使用带控制器的Spring MVC,我的问题是如何返回一个JSON响应,该响应与@ResponseBody对象不同,该对象被返回并且包含在要返回的JSON中。

To elaborate further, I have the object called "UserDetails" which has two fields called "name", "emailAddress" 为了进一步说明,我有一个名为“UserDetails”的对象,它有两个名为“name”,“emailAddress”的字段

@ResponseBody UserDetails

now the json returned will look like 现在json返回的样子

{ name : "TheUsersName", emailAddress:"abc@abc123.com" } {name:“TheUsersName”,emailAddress:“abc@abc123.com”}

Is there any way I can modify the json before returning (ALL jsons in all methods across all controllers) where a "status" field will be added and the other json data will be under the "data" key in the json. 有什么办法可以在返回之前修改json(所有控制器中所有方法中的所有jsons),其中将添加“status”字段,而其他json数据将位于json中的“data”键下。

Also how do I return a json to the frontend when the java server from somewhere throws an exception, the json should have "status : false" and the exception name (atleast the status part though) 另外当从某个地方的java服务器抛出异常时,如何将json返回到前端,json应该具有“status:false”和异常名称(尽管至少是状态部分)

Create a response class: 创建响应类:

public class Response<T> {
    T data;
    boolean status = true;

    public Response(T d) { data = d; }
}

Then return that from your controllers: 然后从您的控制器返回:

@ResponseBody public Response getUserDetails) {
    //...
    return new Response(userDetails);
}

For the exception you'll want to return an object like: 对于异常,您需要返回如下对象:

public class BadStatus {
    String errorMessage;
    boolean status = false;

    public BadStatus(String msg) { errorMessage = msg; }
}

@ExceptionHandler(Exception.class)
public BadStatus handleException(Exception ex, HttpServletRequest request) {
  return new BadStatus(ex.getMessage());
}

An alternate solution (works with spring 3.1), which is less invasive 另一种解决方案(适用于弹簧3.1),其侵入性较小

in your spring config : 在你的春天配置:

<bean id="jacksonConverter"     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="mypackage.MyMessageConverter"
            p:delegate-ref="jacksonConverter">
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

The idea is to provide your own HttpMessageConverter that delegates to the provided jackson converter. 我们的想法是提供您自己的HttpMessageConverter,它委托给提供的jackson转换器。

public class MyMessageConverter implements HttpMessageConverter<Object> {
// setters and delegating overrides ommitted for brevity
@Override
    public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {
// t is whatever your @ResponseBody annotated methods return
        MyPojoWrapper response = new MyPojoWrapper(t);

        delegate.write(response, contentType, outputMessage);
    }
}

This way all your pojos are wrapped with some other json that you provide there. 这样你所有的pojos都会被你提供的其他json包裹起来。

For exceptions, the solution proposed by ericacm is the simplest way to go (remember to annotate the 'BadStatus' return type with @ResponseBody). 对于例外,ericacm提出的解决方案是最简单的方法(记得用@ResponseBody注释'BadStatus'返回类型)。

A caveat : your json-serialized BadStatus goes through MyMessageConverter too, so you will want to test for the object type in the overriden 'write' method, or have MyPojoWrapper handle that. 需要注意的是:您的json序列化BadStatus也会通过MyMessageConverter,因此您需要在重写'write'方法中测试对象类型,或者让MyPojoWrapper处理它。

Yes. 是。 Return a model and a view instead. 返回模型和视图。

public ModelMap getUserDetails() {
    UserDetails userDetails; // get this object from somewhere
    ModelMap map = new ModelMap()(;
    map.addAttribute("data", userDetails);
    map.addAttribute("success", true);
    return map;
}

To add the exception you'd do it the same way with a key and success = false. 要添加异常,您可以使用密钥和success = false以相同的方式执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM