RESTful的理解
程序员文章站
2024-03-25 19:30:46
...
RESTful的理解
- 首先REST只是一种风格,不是一种标准
- REST是以资源为中心
- REST充分利用(极端依赖)HTTP协议(增删改查,传统的mvc框架一般只用到了get与post)
特点为:显示的使用不同的http请求方法
1. 在服务器上创建资源你使用post方式传输
2. 若要是检索资源用get方式传输
3. 若要更改某个资源使用put方式传输
4. 删除某个资源使用delete方式传输
读取) [GET] http://www.example.com/photo/logo
仍然保持为 [GET] http://www.example.com/photo/logo
(创建)http://www.example.com/photo/logo/create
改为 [POST] http://www.example.com/photo/logo
(更新)http://www.example.com/photo/logo/update
改为 [PUT] http://www.example.com/photo/logo
(删除)http://www.example.com/photo/logo/delete
改为 [DELETE] http://www.example.com/photo/logo
信息的传递:目录结构式的URL
实例:http://www.example.com/photo/2010/02/22/{topic}
//使用REST风格传输
http://www.example.com/photo/{year}/{day}/{month}/{topic}
//传统的
http://www.example.com/photo?year=xxxx&day=xxx$month=xxx&topic=xxxx
安全问题:REST可以使用简单有效的安全模型
1. 不发布他的URL
2. 可以根据接收方式对其进行限制,堵塞资源,get只读,post只写等
代码示例:
Controller 代码
@Controller
public class ArticleController {
@RequestMapping(value = "/article/{category}/{id}", method = RequestMethod.GET)
public ModelAndView loadArticle(@PathVariable String category, @PathVariable int id,
@RequestParam(value = "mode", required = false) String mode) {
// ...
}
@RequestMapping(value = "/article", method = RequestMethod.GET)
public ModelAndView loadArticleCategories() {
// ...
}
@RequestMapping(value = "/article", method = RequestMethod.DELETE)
public ModelAndView delArticleCategories() {
// ...
}
@RequestMapping(value = "/addarticle", method = RequestMethod.POST)
public ModelAndView addArticleCategories(Category category) {
// ...
}
@RequestMapping(value = "/addarticle/{name}", method = RequestMethod.POST)
public ModelAndView addArticleCategoriesForName(@PathVariable String name) {
// ...
}
}
调用
@Component("articleClient")
public class ArticleClient {
@Autowired
protected RestTemplate restTemplate;
private final static String articleServiceUrl = "http://localhost:8082/articleservice/";
@SuppressWarnings("unchecked")
public List<Category> getCategories() {
return restTemplate.getForObject(articleServiceUrl + "article", List.class);
}
public Article getArticle(String category, int id) {
return restTemplate.getForObject(articleServiceUrl + "article/{category}/{id}", Article.class, category, id);
}
@SuppressWarnings("unchecked")
public void delCategories() {
restTemplate.delete(articleServiceUrl + "article");
}
@SuppressWarnings("unchecked")
public List<Category> postCategories() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "jizhong");
return restTemplate.postForObject(articleServiceUrl + "addarticle/{name}", null, List.class, params);
}
}