我正在使用 Spring Framework 4.0.7,以及 MVC 和 Rest
我可以安心地工作:
@Controller
ResponseEntity<T>
例如:
@Controller @RequestMapping("/person") @Profile("responseentity") public class PersonRestResponseEntityController {
用方法(只是为了创建)
@RequestMapping(value="/", method=RequestMethod.POST) public ResponseEntity<Void> createPerson(@RequestBody Person person, UriComponentsBuilder ucb){ logger.info("PersonRestResponseEntityController - createPerson"); if(person==null) logger.error("person is null!!!"); else logger.info("{}", person.toString()); personMapRepository.savePerson(person); HttpHeaders headers = new HttpHeaders(); headers.add("1", "uno"); //http://localhost:8080/spring-utility/person/1 headers.setLocation(ucb.path("/person/{id}").buildAndExpand(person.getId()).toUri()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }
归还某物
@RequestMapping(value="/{id}", method=RequestMethod.GET) public ResponseEntity<Person> getPerson(@PathVariable Integer id){ logger.info("PersonRestResponseEntityController - getPerson - id: {}", id); Person person = personMapRepository.findPerson(id); return new ResponseEntity<>(person, HttpStatus.FOUND); }
工作正常
我可以这样做 :
@RestController
@ResponseBody
@ResponseStatus
@RestController @RequestMapping("/person") @Profile("restcontroller") public class PersonRestController {
@RequestMapping(value="/", method=RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void createPerson(@RequestBody Person person, HttpServletRequest request, HttpServletResponse response){ logger.info("PersonRestController - createPerson"); if(person==null) logger.error("person is null!!!"); else logger.info("{}", person.toString()); personMapRepository.savePerson(person); response.setHeader("1", "uno"); //http://localhost:8080/spring-utility/person/1 response.setHeader("Location", request.getRequestURL().append(person.getId()).toString()); }
@RequestMapping(value="/{id}", method=RequestMethod.GET) @ResponseStatus(HttpStatus.FOUND) public Person getPerson(@PathVariable Integer id){ logger.info("PersonRestController - getPerson - id: {}", id); Person person = personMapRepository.findPerson(id); return person; }
我的问题是:
ResponseEntity旨在表示整个 HTTP 响应。您可以控制其中的任何内容:状态代码、标题和正文。
ResponseEntity
@ResponseBody是 HTTP 响应正文的标记,并@ResponseStatus声明了 HTTP 响应的状态代码。
@ResponseStatus不是很灵活。它标记了整个方法,因此您必须确保您的处理程序方法始终以相同的方式运行。而且您仍然无法设置标题。你需要HttpServletResponse.
HttpServletResponse
基本上,ResponseEntity可以让您做更多事情。