SPRING MVC3.2案例讲解--SPRING MVC3的@ResponseBody和ResponseEntity

在传统的开发过程中,我们的控制CONTROLL层通常需要转向一个JSP视图;但随着WEB2.0相关技术的崛起,我们很多时候只需要返回数据即可,而不是一个JSP页面。

 

SPRING MVC3的@ResponseBody使Controller直接返回数据,而不是直接指向具体的视图;同时通过

MessageConverter和produces(如produces="text/plain;charset=UTF-8")可以返回各种格式的数据(XML,json,RSS,TEXT,字节流等),本章只介绍最简单的使用;

见代码:

@ResponseBody可以直接返回结果,

而ResponseEntity 可以定义返回的HttpHeaders和HttpStatus,见文章最后的两张图

 

@RequestMapping(value="/response", method=RequestMethod.GET)
public class ResponseController {

//http://127.0.0.1:8010/response/annotation
	@RequestMapping("/annotation")
	public @ResponseBody String responseBody() {
		return "The String ResponseBody";
	}


	@RequestMapping("/charset/accept")
	public @ResponseBody String responseAcceptHeaderCharset() {
		return "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01 (\"Hello world!\" in Japanese)";
	}

//http://127.0.0.1:8010/response/charset/produce
	@RequestMapping(value="/charset/produce", produces="text/plain;charset=UTF-8")
	public @ResponseBody String responseProducesConditionCharset() {
		return "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01 (\"Hello world!\" in Japanese)";
	}

//http://127.0.0.1:8010/response/entity/status
	@RequestMapping("/entity/status")
	public ResponseEntity<String> responseEntityStatusCode() {
		return new ResponseEntity<String>("The String ResponseBody with custom status code (403 Forbidden)",
				HttpStatus.FORBIDDEN);
	}

//http://127.0.0.1:8010/response/entity/headers
	@RequestMapping("/entity/headers")
	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);
	}

}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值