[springmvc]Generating responses

本文介绍了SpringMVC中两种常见的响应处理方式:使用@ResponseBody注解直接返回POJO对象作为响应体内容,以及创建并返回ResponseEntity对象以提供更灵活的响应控制。

1. Return a POJO annotated with @ResponseBody: POJO marshaled as the body of the response

    @RequestMapping(value="/response/annotation", method=RequestMethod.GET)
public @ResponseBody String responseBody() {
return "The String ResponseBody";
}

@RequestMapping(value="/response/charset/accept", method=RequestMethod.GET)
public @ResponseBody String responseAcceptHeaderCharset() {
return "こんにちは世界! (\"Hello world!\" in Japanese)";
}

@RequestMapping(value="/response/charset/produce", method=RequestMethod.GET, produces="text/plain;charset=UTF-8")
public @ResponseBody String responseProducesConditionCharset() {
return "こんにちは世界! (\"Hello world!\" in Japanese)";
}

2. Return a new ResponseEntity<T> object

    @RequestMapping(value="/response/entity/status", method=RequestMethod.GET)
public ResponseEntity<String> responseEntityStatusCode() {
return new ResponseEntity<String>("The String ResponseBody with custom status code (403 Forbidden)",
HttpStatus.FORBIDDEN);
}

@RequestMapping(value="/response/entity/headers", method=RequestMethod.GET)
public ResponseEntity<String> responseEntityCustomHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<String>("The String ResponseBody with custom header Content-Type=text/plain",
headers, HttpStatus.OK);
}




转载于:https://www.cnblogs.com/lavieenrose/archive/2012/03/26/2418754.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值