即使Accept被定义为null,也会调用@GetMapping

问题描述 投票:1回答:1

我正在使用Spring Framework 4.3.13.RELEASE

关于休息,对于POST,我有以下内容:

@Controller
@RequestMapping(path="/personas")
public class PersonaRestController {

    @PostMapping(consumes={MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<Void> saveOne(
            @Validated @RequestBody Persona persona, ...

关于使用JUnitResultActions进行测试我可以得到java.lang.AssertionError: No handler错误消息并确认以下内容:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /personas
       Parameters = {}
          Headers = {}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotSupportedException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = {Accept=[application/xml, application/json;charset=UTF-8]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

感觉这种行为是因为saveOne方法期望内容数据是XMLJSON,并且对于这个测试场景,没有发送Content-Type

因此,预计春天会出现一个HttpMediaTypeNotSupportedException实例。然后@Test方法失败并出现java.lang.AssertionError: No handler错误消息,因为没有处理用户请求的处理程序。

直到这里一切都好。

再次,关于休息,对于GET,我有以下内容:

@GetMapping(path="/{id}",
            produces={MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE})
public @ResponseBody Persona findOneById(@PathVariable String id){
    return personaService.findOneById(id);
}

对于具有以下内容的其他测试方案:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /personas/100
       Parameters = {}
          Headers = {}

Handler:
             Type = com.manuel.jordan.rest.persona.PersonaRestController
           Method = public com.manuel.jordan.domain.Persona com.manuel.jordan.rest.persona.PersonaRestController.findOneById(java.lang.String)

我的拦截器显示以下数据

HttpHeaderControlInterceptor - preHandle 
   HttpServletRequest > 
    URL: http://localhost/personas/100 
    URI: /personas/100 
       HttpMethod: GET 
          Accept: null 
          Accept-Language: null 
          Content-Type: null 

我很困惑为什么findOneById方法被称为处理程序,即使Accept为null。我曾经期望类似于java.lang.AssertionError: No handler错误消息和HttpMediaTypeNotAcceptableException类,它因为findOneById方法可以返回XMLJSON中的数据

缺什么?

spring spring-mvc spring-rest
1个回答
1
投票

我不完全确定,但猜测它是由HTTP 1.1引起的,

见章节 - 10.4.7 406不可接受的here

注意:允许HTTP / 1.1服务器根据请求中发送的接受标头返回不可接受的响应。在某些情况下,这甚至可能比发送406响应更可取。鼓励用户代理检查传入响应的标头以确定它是否可接受。

我认为,consumesproduces的治疗是不同的,这就是你看到差异的原因。

请参阅此SO问题here

在我删除之前,我已经发布了一个答案。基本上,我误解了你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.