restful风格,restcontroller与controller
2017-09-29 11:52
375 查看
restful风格
简单的理解,restful是一种url风格,或者说是规范,在以前的网址中,假定一个业务,取得数据网址为http://test/get,添加信息的网址为http://test/post,类似这样。 但是在restful风格中,取得数据和添加数据的网址均应为http://test,方法为get或者post;所以,在restful风格中,一个网址就是一个资源,其形式类似于http://xxx.com/xx/{id}/{id}
,例如某购物网站,产品有很多种类,每种产品下有很多子类型,那么http://shop.com/laptop/lenovo/1103 代表了联想1103型号电脑,而http://shop.com/laptop/hp/1024 代表了2014型号电脑。
在spring mvc中,有@requestparm, @requestbody和@pathvariable 三种注解来获得浏览器端的参数,其中前两者都是由浏览器post提交的参数,而@pathvariable 则是从网址中取得参数;假设代码如下:
@Requestmapping(value="/{category}/{brand}/{id},method=RequestMethod.POST) public void getbyid(@PathVariable("category") String category @PathVariable("brand") String brand @PathVariable("id") String id){ //具体代码略 }在上述代码中,访问http://shop.com/laptop/hp/1024网址时,则,category为“laptop”,brand为”hp”,id为”1024”;所以说,在restful风格中,一个网址即表示了一个资源。[/code]
restcontroller与controller
假定一个user对象,对象有很多属性(name,sex,age,birth,address,tel) 在我的了解中,这二者的区分为:@restcontroller为@controller和@responsebody的结合
在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的,
在这种情况下,前后端的配合要求比较高,java后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)的数据将填充user视图中的相关属性,然后展示到浏览器,这个过程也可以称为渲染;
java示例代码如下:
@Controller @RequestMapping(method = RequestMethod.GET, value = "/") public String getuser(Model model) throws IOException { model.addAttribute("name",bob); model.addAttribute("sex",boy); return "user";//user是模板名 }对应视图user.jsp中的html代码:[/code]
<html xmlns:th="http://www.thymeleaf.org"> <body> <div> <p>"${name}"</p> <p>"${sex}"</p> </div> </body> </html>而在@restcontroller中,返回的应该是一个对象,即return一个user对象,这时,在没有页面的情况下,也能看到返回的是一个user对象对应的json字符串,而前端的作用是利用返回的json进行解析渲染页面,java后端的代码比较自由。 [/code]
java端代码:
@RestController @RequestMapping(method = RequestMethod.GET, value = "/") public User getuser( ) throws IOException { User bob=new User(); bob.setName("bob"); bob.setSex("boy"); return bob; }
访问网址得到的是json字符串{“name”:”bob”,”sex”:”boy”},前端页面只需要处理这个字符串即可。
http://blog.csdn.net/pinebud55/article/details/52183238?locationNum=12
相关文章推荐
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller详解
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller
- restful风格,restcontroller与controller
- SpringMVC提供@RestController Restful风格
- 前后端关系,restful风格,restcontroller与controller区别
- Spring入门学习(二)RESTful风格的Controller
- Yii2.0 RESTful风格的Controller与ActiveController
- restful风格,@RestController和@Controller的区别
- Spring MVC-Controller和@RequestMapping ModelAndView配置和用法-restful风格
- 在Dubbo中开发REST风格的远程调用(RESTful Remoting)
- 理解并设计rest/restful风格接口
- SpringMVC学习之RESTful风格post
- RESTful风格实现拦截登录
- restful 风格API 实践