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 三种注解来获得浏览器端的参数,其中@requestparm是取自url中“?”之后的a=b&c=d,@requestbody 来自于请求体,而@pathvariable 则是从网址中取得参数;
感谢评论区@comeoon的订正,浏览器的get/put/delete/post方法都可以使用上述参数,但是由于浏览器get方法不能提供body,所以RequestBody实际获取的是一个map,参数来自于url中“?”之后的参数(实际上是request parameters)
假设代码如下:
@Requestmapping(value="/{category}/{brand}/{id},method=RequestMethod.POST) public void getbyid(@PathVariable("category") String category @PathVariable("brand") String brand @PathVariable("id") String id){ //具体代码略 }
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"; }对应的html代码:
<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后端的代码比较自由。
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”},前端页面只需要处理这个字符串即可。
如侵删