SpringMVC Restful风格

143 阅读1分钟

概念

一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

URL定义

资源:互联网所有的事物都可以被抽象为资源 
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。 
分别对应 添加、 删除、修改、查询。

传统方式操作资源︰

通过不同的参数来实现不同的效果!
方法单一,post和get
. http://127.0.0.1/item/queryltem.action?id=1 (查询,GET)
. http://127.0.0.1/item/saveltem.action (新增,POST)
. http://127.0.0.1/item/updateltem.action (更新,POST)
. http://127.0.0.1/item/deleteltem.action?id=1 (删除,GET或POST)

使用RESTful操作资源︰

可以通过不同的请求方式来实现不同的效果!
请求地址一样,但是功能可以不同!
. http://127.0.0.1/item/1 (查询,GET)
. http://127.0.0.1/item (新增,POST)
. http://127.0.0.1/item (更新,PUT)
. http://127.0.0.1/item/1 (删除,DELETE)

样例

  • 传统方法
@Controller
public class RestfulTest {
    @RequestMapping("/add")
    public String test(int a,int b,Model model){
        model.addAttribute("msg","result="+(a+b));
        return "restful";
    }
}
  • Restful风格
@Controller
public class RestfulTest {
    @RequestMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable int b, Model model){
        model.addAttribute("msg","result="+(a+b));
        return "restful";
    }
}

image.png

同样的rul处理不一样的请求

public class RestfulTest {
    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.POST)
    public String test(@PathVariable int a, @PathVariable int b, Model model){
        model.addAttribute("msg","result="+(a+b)+"post");
        return "restful";
    }
    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
    public String test1(@PathVariable int a, @PathVariable int b, Model model){
        model.addAttribute("msg","result="+(a+b)+"get");
        return "restful";
    }
}

image.png image.png

image.png