1

给定以下 Spring 代码:

@Controller
@RequestMapping("/somepath")
public class SomeService {
    @RequestMapping(headers = "Accept=application/json")
    public ReturnType methodOne() {
        // stuff
    }

    @RequestMapping(headers = "Accept=text/html")
    public ReturnType methodTwo() {
        // stuff
    }
}

我注意到,当客户端根本不包含“Accept”标头时,总是优先调用“application/json”方法而不是 text/html 方法。我的问题是——为什么?它们之间没有什么可以选择的,那么为什么更喜欢其中一个呢?我本来希望收到一条错误消息...

一个具体的例子:

@RequestMapping("/somepath")
@Controller
public class SomeService {

    @ResponseBody
    @RequestMapping(headers = "Accept=application/json")
    public ResponseEntity<String> methodOne() {
        return new ResponseEntity<String>("Method One", HttpStatus.OK);
    }

    @ResponseBody
    @RequestMapping(headers = "Accept=text/html")
    public ResponseEntity<String> methodTwo() {
        return new ResponseEntity<String>("Method Two", HttpStatus.OK);
    }

    @ResponseBody
    @RequestMapping(headers = "Accept=application/xml")
    public ResponseEntity<String> methodThree() {
        return new ResponseEntity<String>("Method Three", HttpStatus.OK);
    }
}

如果没有接受标头,则始终输出“方法一”。

4

1 回答 1

0

Spring doesn't prefer anything. It can return whatever you specify (pdf, xml, etc)

However, JSON is commonly implented as views often interact with controllers using javascript and ajax. What data format is best to use with javascript : JSON.

于 2012-11-15T15:30:39.243 回答