Spring MVC 返回 JSONS 和异常处理

发布于 2024-10-24 23:03:52 字数 614 浏览 1 评论 0原文

我将 Spring MVC 与控制器一起使用,我的问题是如何返回一个 JSON 响应,该响应与返回并转换为要返回的 JSON 的 @ResponseBody 对象不同。

为了进一步详细说明,我有一个名为“UserDetails”的对象,它有两个名为“name”、“emailAddress”的字段,

@ResponseBody UserDetails

现在返回的 json 看起来像

{ name : "用户名", emailAddress:"[电子邮件受保护]" }

有什么方法可以修改返回之前的 json(所有控制器的所有方法中的所有 json),其中将添加“status”字段,其他 json 数据将位于 json 中的“data”键下。

另外,当 java 服务器从某个地方抛出异常时,如何将 json 返回到前端,json 应该具有“status : false”和异常名称(至少是状态部分)

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.

To elaborate further, I have the object called "UserDetails" which has two fields called "name", "emailAddress"

@ResponseBody UserDetails

now the json returned will look like

{ name : "TheUsersName",
emailAddress:"[email protected]" }

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.

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无人问我粥可暖 2024-10-31 23:03:52

创建一个响应类:

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

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

然后从控制器返回该响应类:

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

对于异常,您需要返回一个如下对象:

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());
}

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());
}
掩耳倾听 2024-10-31 23:03:52

是的。相反,返回模型和视图。

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

要添加异常,您可以使用 key 和 success = false 以相同的方式执行此操作。

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.

蝶舞 2024-10-31 23:03:52

另一种解决方案(适用于 spring 3.1),它对

spring 配置的侵入性较小:

<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>

其想法是提供您自己的 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);
    }
}

这样,您的所有 pojo 都会用您在那里提供的其他一些 json 进行包装。

对于例外情况,ericacm 提出的解决方案是最简单的方法(请记住使用 @ResponseBody 注释“BadStatus”返回类型)。

需要注意的是:您的 json 序列化的 BadStatus 也会通过 MyMessageConverter,因此您需要在重写的“write”方法中测试对象类型,或者让 MyPojoWrapper 处理该类型。

An alternate solution (works with spring 3.1), which is less invasive

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.

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.

For exceptions, the solution proposed by ericacm is the simplest way to go (remember to annotate the 'BadStatus' return type with @ResponseBody).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文