1. 可以这么去理解RESTful:其实就是web对外提供的一种基于URL、URI的资源供给服务。不是一个原理性知识点。是一个方法论和规范标准!
2. 利用HTTP的四个方法请求:POST/GET/DELETE/PUT。
完全可以使用RESTful对系统进行增删改查的操作!
3. springREST API:利用spring的几个特点
在接收URL请求的时候,在@RequestMapping里可以用一个变量占位来接收请求的URL值!这个可以使得URL中可以携带一些需要查询的变量值向后台请求。如:http:///user/23u59t4。
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json; charset=utf-8")
public ResponseEntity deleteUser(@PathVariable Long id)
{
User user = userService.findById(id);
if (user == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
userService.deleteUser(id);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
当然,一定可以解析类似GET请求的表单查询方式的:http:/www.baidu.com?user=23u59t4
如下来自spring官方文档的一个基于spring的java RESTful后台例子:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
其中@RestController的作用(官方文档原文):
This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @ResponseBody rolled together.
意思是,在这个声明一个类为REST controller类,然后这个类里的所有响应方法的response返回都不是view(不需要进行视图解析!)只返回实体数据如:json、xml之类的...
而不像普通的@Controller注解声明的类,它的响应方法需要加上@ResponseBody才能表明这个响应是返回主体!
4. 前端可以使用AJAX发送请求。也可以直接在浏览器的地址栏中加载这个RESTful URL!