restful的认识和用法

1502888-20190525160420176-316249487.png

一、restful的认识

1、基本概念

(1)REST指的是一组架构约束条件和原则。 如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。REST的意思是资源的表述性状态转移
(2)先看REST是什么意思,英文Representational state transfer 表述性状态转移。其实就是对 资源 的表述性状态转移。

什么是表述性:就是指客户端请求一个资源,服务器拿到的这个资源,就是表述
资源的地址 在web中就是URL (统一资源标识符)
资源是REST系统的核心概念。 所有的设计都是以资源为中心

(3)RESTful架构与传统的RPC、SOAP等方式在理念上有很大的不同
(4)目的:实现客户端无需借助任何文档即能调用到所有的服务器资源。客户只可以通过服务端所返回各结果中所包含的信息来得到下一步操作所需要的信息,如到底是向哪个URL发送请求等。

2、规范和约束

RESTful 架构的核心规范与约束:统一接口。
分为四个子约束:
(1)每个资源都拥有一个资源标识,每个资源的资源标识可以用来唯一地标明该资源

就是写在controller上的访问路径

(2)消息的自描述性

比如Content-Type可以为application/x-www-form-urlencoded(标准的编码格式)、application/json、text/plain、application/xml、text/html

(3)资源的自描述性。

就是所带的参数

(4)超媒体作为应用状态引擎

一个网站里面肯定还有很多其他链接,链接到新链接,且链接容易被标识。

3、使用标准的状态码

(1)GET

安全且幂等
表示获取
200(OK) - 表示已在响应中发出
204(无内容) - 资源有空表示
301(Moved Permanently) - 资源的URI已被更新
303(See Other) - 其他(如,负载均衡)
304(not modified)- 资源未更改(缓存)
400 (bad request)- 指代坏请求(如,参数错误)
404 (not found)- 资源不存在
406 (not acceptable)- 服务端不支持所需表示
500 (internal server error)- 通用错误响应
503 (Service Unavailable)- 服务端当前无法处理请求

(2)POST

不安全且不幂等
创建子资源
部分更新资源
200(OK)- 如果现有资源已被更改
201(created)- 如果新资源被创建
202(accepted)- 已接受处理请求但尚未完成(异步处理)
301(Moved Permanently)- 资源的URI被更新
303(See Other)- 其他(如,负载均衡)
400(bad request)- 指代坏请求
404 (not found)- 资源不存在
406 (not acceptable)- 服务端不支持所需表示
409 (conflict)- 通用冲突
412 (Precondition Failed)- 前置条件失败(如执行条件更新时的冲突)
415 (unsupported media type)- 接受到的表示不受支持
500 (internal server error)- 通用错误响应
503 (Service Unavailable)- 服务当前无法处理请求

(3)PUT

不安全但幂等
通过替换的方式更新资源
200 (OK)- 如果已存在资源被更改
201 (created)- 如果新资源被创建
301(Moved Permanently)- 资源的URI已更改
303 (See Other)- 其他(如,负载均衡)
400 (bad request)- 指代坏请求
404 (not found)- 资源不存在
406 (not acceptable)- 服务端不支持所需表示
409 (conflict)- 通用冲突
412 (Precondition Failed)- 前置条件失败(如执行条件更新时的冲突)
415 (unsupported media type)- 接受到的表示不受支持
500 (internal server error)- 通用错误响应
503 (Service Unavailable)- 服务当前无法处理请求

(4)DELETE

不安全但幂等
删除资源
200 (OK)- 资源已被删除
301 (Moved Permanently)- 资源的URI已更改
303 (See Other)- 其他,如负载均衡
400 (bad request)- 指代坏请求
404 (not found)- 资源不存在
409 (conflict)- 通用冲突
500 (internal server error)- 通用错误响应
503 (Service Unavailable)- 服务端当前无法处理请求

二、具体使用

1、简单概括

url请求方式作用
/emp/{id}GET查询一个员工
/empGET查询所有员工
/empPOST保存一个员工
/emp/{id}PUT修改一个员工
/emp/{id}DELETE删除一个员工

2、根据id查询一个员工

------controller端-----

@RequestMapping("/emp/{empId}")
@ResponseBody
public Emp getEmpById(@PathVariable Long empId) {
    Emp emp= empService.getEmpById(empId);
    return emp;
}
<!--Emp就一个pojo-->

------serviceImpl端-----

@Override
public Emp getEmpById(long empId) {
    Emp emp = empMapper.selectByPrimaryKey(empId);
    return emp;
}

------前端的ajax-----

function getEmp(empId){
    $.ajax({
        url : "${Pro_Path}/emp/"+empId,
        type : "GET",
        //请求成功的回调函数
        success : function(result) {
            $("#一个input的id").val(result.empName);
        }
    });
}

3、查询所有员工

------controller端-----

<!-- 分页查询的参数:page传入页码,rows以及每页的大小-->
@RequestMapping("/emp/list")
@ResponseBody
public PageInfo getEmpList(Integer page, Integer rows) {
    return empService.getEmpList(page, rows);
}

------serviceImpl端-----

public PageInfo getEmpList(int page, int rows) {
    //设置分页信息
    PageHelper.startPage(page, rows);
    //执行查询
    EmpExample example = new EmpExample();
    List<Emp> list = empMapper.selectByExample(example);
    //取查询结果
    PageInfo<Emp> pageInfo = new PageInfo<>(list);
    //返回结果
    return pageInfo;
}

------前端的ajax-----

function to_page(page) {
    $.ajax({
        url : "${Pro_Path}/emp/list",
        data: '{"page": page, "rows": 8}',
        type : "GET",
        //请求成功的回调函数
        success : function(result) {
                //数据表单展示:
                $.each(result.list,function(index, item) {
                    //将表格内容显示出来
                    var checkBoxTd=$("<td><input type='checkbox'/></td>");
                    var empIdTd = $("<td></td>").append(item.empId);
                    var empNameTd = $("<td></td>").append(item.empName);
                    $("<tr></tr>").append(checkBoxTd).append(empIdTd).append(empNameTd).appendTo("#tbody的id");
                });
                页面情况展示:
                $("#div的id").append("当前第" + result.pageNum + "页  共有" + result.pages+ "页  总计" + result.total + "条记录");
                页数导航:
                var ul = $("<ul></ul>");
                $.each(result.navigatepageNums, function(index, item) {
                    var eachPgaeNumLi = $("<li></li>").append(
                            $("<a></a>").append(item));
                    //添加单击事件
                    eachPgaeNumLi.click(function() {
                        to_page(item);
                    });
                    ul.append(eachPgaeNumLi);
                });
                var navEle = $("<nav></nav>").append(ul);
                navEle.appendTo("#div的id");
        }
    });
}

4、保存一个员工

------controller端-----

//保存员工(一般有用到jsr303校验)
@RequestMapping(value="/saveEmp",method=RequestMethod.POST)
@ResponseBody
public DataResult saveEmp(@Valid Employee employee,BindingResult result) {
    if(result.hasErrors()) {
        Map<String,Object> map=new HashMap<String,Object>();
        //result校验失败,应该返回失败 ,在模态框中显示校验失败的错误信息
        List<FieldError> errors=result.getFieldErrors();
        for (FieldError fieldError : errors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        DataResult.build( DataResult.error ,null, map);
    }else {
        return employeeService.saveEmp(employee);
    }
}
<!--DataResult是一个处理结果的pojo,
包含属性 :
响应业务状态 private Integer status; 
响应消息 private String msg;
响应中的数据 private Object data; -->

------serviceImpl端-----

public DataResult saveEmp(Employee employee) {
    employeeMapper.insertSelective(employee);
    return DataResult.ok();
}

------前端的ajax-----

$.ajax({
    url:"${Pro_Path}/saveEmp",
    type:"POST",
    data:$("#form的id").serialize(),
    success:function(result){
        //保存成功后:
        if(result.status==100){
            。。。此处省略。。。
        }else{
            // 保存失败后
            //如果有邮箱的错误信息
            if(result.data.email!=undefined){
                    。。。此处省略。。。
            }
            //如果有用户名的错误
            if(result.data.empName!=undefined){
                    。。。此处省略。。。
            }
        }               
    }
});

5、根据id修改员工

------controller端-----

/*
 * 根据id修改员工
 * 注意传递的id名字要和Employee 的属性名一样
 */
@RequestMapping(value="/updateEmp/{empId}",method=RequestMethod.PUT)
@ResponseBody
public DataResult updateEmp(Employee employee) {
    return employeeService.updateEmp(employee); 
}

------serviceImpl端-----

public DataResult updateEmp(Employee employee) {
        employeeMapper.updateByPrimaryKeySelective(employee);
        return DataResult.ok();
}

------前端的ajax-----

var id=$(this).attr("edit-id");
$.ajax({
    url : "${Pro_Path}/updateEmp/"+id,
    type : "POST",
    data:$("#form的id").serialize()+"&_method=PUT",
    success : function(result) {
    
    }
});

6、删除一个员工

------controller端-----

    @RequestMapping(value="/deleteEmpById/{id}",method=RequestMethod.DELETE)
    @ResponseBody
    public DataResult deleteEmpById(@PathVariable("id")Integer id) {
        return employeeService.deleteEmpById(id);
    }

------serviceImpl端-----

public DataResult deleteEmpById(Integer id) {
    employeeMapper.deleteByPrimaryKey(id);  
    return DataResult.ok();
}

------前端的ajax-----

$.ajax({
    url : "${Pro_Path}/deleteEmpById/"+empId,
    type : "DELETE",
    success : function(result) {
        
    }
});

7、批量删除多个员工

------controller端-----

@RequestMapping(value="/deleteEmpsById/{ids}",method=RequestMethod.DELETE)
@ResponseBody
public ProcessMsg deleteEmpsById(@PathVariable("ids")String ids) {
    //如果是多个id
    if(ids.contains("-")) {
        String[] str_id=ids.split("-");
        List<Integer> list_id=new ArrayList<Integer>();
        for(String item_id:str_id) {
            list_id.add(Integer.parseInt(item_id));
        }
        return employeeService.deleteBatch(list_id);
    //如果是一个id
    }else {
        return employeeService.deleteEmpById(Integer.parseInt(ids));
    }
}

------serviceImpl端-----

public DataResult deleteBatch(List<Integer> str_id) {
    EmployeeExample employeeExample=new EmployeeExample();
    Criteria criteria=employeeExample.createCriteria();
    criteria.andEmpIdIn(str_id);
    employeeMapper.deleteByExample(employeeExample);
    return DataResult.ok();
}
public DataResult deleteEmpById(Integer id) {
    employeeMapper.deleteByPrimaryKey(id);  
    return DataResult.ok();
}

------前端的ajax-----

$("#emp_delete_all_btn").click(function() {
    var del_id_str="";
    $.each($(".check_item:checked"),function(){
        del_id_str+=$(this).parents("tr").find("td:eq(1)").text()+"-";
    });
    //去除最后一个逗号,分号
    del_id_str=del_id_str.substring(0 , del_id_str.length-1);
    $.ajax({
        url : "${Pro_Path}/deleteEmpsById/"+del_id_str,
        type : "DELETE",
        success : function(result) {

        }
    });
});

转载于:https://www.cnblogs.com/ranandrun/p/restful.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值