Spring MVC returning JSONS and exception Handling

后端 未结 3 925
庸人自扰
庸人自扰 2021-02-06 07:33

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 JSO

相关标签:
3条回答
  • 2021-02-06 08:21

    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());
    }
    
    0 讨论(0)
  • 2021-02-06 08:25

    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.

    0 讨论(0)
  • 2021-02-06 08:30

    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.

    0 讨论(0)
提交回复
热议问题