使用spring @RestController在null上返回HTTP 204

时间:2015-09-04 11:23:53

标签: java spring spring-mvc spring-restcontroller

这将返回200 OK,Content-Length:0

@RestController
public class RepoController {
    @RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
    public Object getDocument(@PathVariable long id) {
       return null;
    }

}

简单地说,我希望它在null上返回204 No Content。

有没有办法强制spring-mvc / rest在null而不是200时返回204?我不想更改每个rest方法以返回ResponseEntity或类似的东西,只将null映射到204

7 个答案:

答案 0 :(得分:35)

您可以使用@ResponseStatus注释。这样您就可以使用void方法,而不必构建ResponseEntity。

@DeleteMapping(value = HERO_MAPPING)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long heroId) {
    heroService.delete(heroId);
}

BTW在对象存在时返回200,否则在API REST设计上有点不寻常。当找不到请求的对象时,返回404(未找到)是很常见的。这可以使用ControllerAdvice来实现。

在Spring REST中,最好使用Exception处理程序处理Exceptions,而不是使用逻辑来决定响应状态等。这是使用@ControllerAdvice批注的示例:http://www.jcombat.com/spring/exception-handling-in-spring-restful-web-service

答案 1 :(得分:21)

当然是的。

选项1:

@RestController
public class RepoController {
    @RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
    public Object getDocument(@PathVariable long id, HttpServletResponse response) {
       Object object = getObject();
       if( null == object ){
          response.setStatus( HttpStatus.SC_NO_CONTENT);
       }
       return object ;
    }
}

选项2:

@RestController
public class RepoController {
    @RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
    public Object getDocument(@PathVariable long id) {
       Object object = getObject();
       if ( null == object ){
          return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
       }

       return object ;
    }
}

可能有拼写错误,但你明白这个概念。

答案 2 :(得分:9)

我用过滤器解决了这个问题。它是全球性和简单的。

package your.package.filter;

import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class NoContentFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        if (httpServletResponse.getContentType() == null ||
                httpServletResponse.getContentType().equals("")) {
            httpServletResponse.setStatus(HttpStatus.NO_CONTENT.value());
        }
    }
}

并在web.xml中添加以下内容

<filter>
    <filter-name>restNoContentFilter</filter-name>
    <filter-class>your.package.filter.NoContentFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>restNoContentFilter</filter-name>
    <url-pattern>/rest/*</url-pattern>
</filter-mapping>

答案 3 :(得分:4)

你可以试试这个:

@RestController
public class RepoController {

    @RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
    public ResponseEntity<String> getDocument(@PathVariable long id) {

       if(noError) {
           ............
           return new ResponseEntity<String>(HttpStatus.OK); 
       }
       else {
           return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
       }
   }
}

您需要更改HttpStatus.BAD_REQUEST,使用等效的204代码状态

答案 4 :(得分:1)

答案相同,但AOP解决了:

@Aspect
public class NoContent204HandlerAspect {

  @Pointcut("execution(public * xx.xxxx.controllers.*.*(..))")
  private void anyControllerMethod() {
  }

  @Around("anyControllerMethod()")
  public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {

    Object[] args = joinPoint.getArgs();

    Optional<HttpServletResponse> response = Arrays.asList(args).stream().filter(x -> x instanceof HttpServletResponse).map(x -> (HttpServletResponse)x).findFirst();

    if (!response.isPresent())
      return joinPoint.proceed();

    Object retVal = joinPoint.proceed();
    if (retVal == null)
      response.get().setStatus(HttpStatus.NO_CONTENT.value());

    return retVal;
  }
}

答案 5 :(得分:1)

问题很旧,但对于需要全局答案且具有Spring 4+的问题,您可以创建一个ResponseBodyAdvice,该响应根据控制器响应来更改响应代码。以下示例对所有@RestController类执行此操作:

@ControllerAdvice(annotations = { RestController.class })
public class NullToNoContentResponseBodyAdvice
    implements ResponseBodyAdvice<Object>
{
    /**
     * {@inheritDoc}
     */
    @Override
    public Object beforeBodyWrite(final Object p_responseBodyObject, final MethodParameter p_methodParameter,
                                  final MediaType p_mediaType, final Class<? extends HttpMessageConverter<?>> p_class,
                                  final ServerHttpRequest p_serverHttpRequest,
                                  final ServerHttpResponse p_serverHttpResponse)
    {
        // ------------------------- DECLARE -------------------------- //

        if (p_responseBodyObject == null)
        {
            p_serverHttpResponse.setStatusCode(HttpStatus.NO_CONTENT);
        }

        // Always return object unchanged or it will break response
        return p_responseBodyObject;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supports(final MethodParameter p_methodParameter, final Class<? extends HttpMessageConverter<?>> p_class)
    {
        return AbstractGenericHttpMessageConverter.class.isAssignableFrom(p_class);
    }
}

答案 6 :(得分:0)

您可以自定义HttpMessageConverter以支持此操作,因为我这样做是在spring.http.converters.preferred-json-mapper=gson配置文件中添加了application.properties,并给出了如下结果建议:

@ControllerAdvice
public class CommonResultAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
    return true;
}

@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

    if (null == o) {
    //set http code
        serverHttpResponse.setStatusCode(HttpStatus.NO_CONTENT);
        return BaseResult.success();
    }

    if (o instanceof String) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(BaseResult.success(o));
        } catch (JsonProcessingException ignore) {
        }
    }

    if (o instanceof BaseResult) {
        return o;
    }
    return BaseResult.success(o);
}

}

或自定义HttpMessageConverter

@Configuration
public class BeanConfiguration {
@Bean
public HttpMessageConverter resultToJsonConverter() {
    return new GsonHttpMessageConverter();
}
}
希望能为您提供帮助。 :)