简体   繁体   English

从spring控制器返回空JSON以获得void响应

[英]Return empty JSON from spring controller for void response

I'm using Java 8, Tomcat 8, Spring-WebMVC 4.2.2.RELEASE, FasterXML 2.6.3. 我正在使用Java 8,Tomcat 8,Spring-WebMVC 4.2.2.RELEASE,FasterXML 2.6.3。

I have the following method in my controller 我的控制器中有以下方法

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public void updateCurrentUserDetails(@RequestBody final UserDTO userDTO) {
    final UserWithId user = SecurityUtil.getCurrentUser();
    this.userAccountService.updateUserDetails(user.getUserId(), user.getUsername(), userDTO);
}

This method returns void which resolves in an empty (0 byte) response. 此方法返回void,该值在空(0字节)响应中解析。 However the clients connecting to the server always expect JSON reponses even, if its an empty response. 但是,连接到服务器的客户端总是希望JSON响应,如果它是空响应。

So I would like to configure Spring/Jackson to return {} (2 byte) in that case. 所以我想配置Spring / Jackson在这种情况下返回{}(2字节)。

I already thought about returning new Object() everywhere in the calls that would return void otherwise but IMO this is a dirty soution and there must be something better. 我已经考虑过在返回无效的调用中返回新的Object(),但IMO这是一个肮脏的问题,必须有更好的东西。

There shouldn't be any need to do all that. 不应该做任何事情。 You can just use a 204 response code, which is made for the situation you are describing. 您可以使用204响应代码,该代码是针对您描述的情况而制定的。 You don't even need the ResponseBody annotation, just use: 您甚至不需要ResponseBody注释,只需使用:

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateCurrentUserDetails(@RequestBody final UserDTO userDTO) {
    final UserWithId user = SecurityUtil.getCurrentUser();
    this.userAccountService.updateUserDetails(user.getUserId(), user.getUsername(), userDTO);
}

204 response code : 204响应代码

The 204 (No Content) status code indicates that the server has 204(无内容)状态代码表示服务器具有
successfully fulfilled the request and that there is no additional 成功完成了请求,并且没有其他要求
content to send in the response payload body. 要在响应有效负载主体中发送的内容。

Its quite easy. 它很容易。

Just add the following to your spring xml/java config 只需将以下内容添加到spring xml / java config即可

<mvc:interceptors>
    <bean class="de.st_ddt.util.VoidResponseHandlerInterceptor" />
</mvc:interceptors>

And add this class to your classpath 并将此类添加到类路径中

public class VoidResponseHandlerInterceptor extends HandlerInterceptorAdapter {

    private static final String voidResponse = "{}";

    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
            final ModelAndView modelAndView) throws IOException {
        // Returned void?
        if (!response.isCommitted()) {
            // Used ModelAndView?
            if (modelAndView != null) {
                return;
            }
            // Access static resource?
            if (DefaultServletHttpRequestHandler.class == handler.getClass()) {
                return;
            }
            response.setStatus(200);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            try (final Writer writer = response.getWriter()) {
                writer.write(voidResponse);
            }
            response.flushBuffer();
        }
    }
}

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

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