RESTful风格(使用Ajax+Spring MVC框架实现)

RESTful简介:
(详情参考:)
http://baike.baidu.com/link?url=1FMTyxYwnN5OED7oXwbLBI1z35JCuE1bfIamqJMrbBUeNDPmQ6U3t-gx9tGHC170A0akfPhhzfBNWF0BwHj-xq
http://developer.51cto.com/art/200908/141825.htm
https://www.zhihu.com/question/28557115
http://blog.csdn.net/aooppo/article/details/8686595

个人理解:
在同一个路径下,不同的协议请求(Get、Post、Put、Delete、Patch、Head、Option s、Trace)实现不同的功能。


一、环境配置
①、开发前的基础配置:配置好相应的Spring MVC、JSON和Restful需要的依赖程序包。
②、Tomcat9.0服务器配置
③、在项目配置web.xml

    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param> 
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 路径是 '/' 斜杠 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

④、建立一个测试类TextRestful .java,测试环境是否可用

@Controller 
public class TextRestful {
    @RequestMapping(value="/restful",produces="text/plain;charset=UTF-8")
    public @ResponseBody String info() {
        return "Hello World!";
    }
}

浏览器输入路径:http://localhost/XXXX(项目名称) / restful(方法路径)
页面显示:Hello World!则代表环境搭建完成。
⑤准备要测试的Vo类

public class Emp implements Serializable {
    private Integer empno;
    private String ename;
    private double sal;
    private Date hiredate;
    //此处省略setter()、getter()和toString()方法
}

⑥准备好测试的test.JSP页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    // request.setCharacterEncoding("UTF-8") ;
%>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/restful.js"></script>
<title>Insert title here</title>
</head>
<body>
    <input type="button" id="addBut" name="addBut" value="增加"><br>
    <input type="button" id="editBut" name="editBut" value="更新"><br>
    <input type="button" id="deleteBut" name="deleteBut" value="删除"><br>
    <input type="button" id="getBut" name="getBut" value="查询"><br>
    <input type="button" id="listBut" name="listBut" value="分页显示"><br>
    <div id="showDiv"></div>
</body>
</html>

二、Restful风格实现CRUD
1、POST请求实现数据增加:
①、在TextRestful.java中增加:

@RequestMapping(value="/restful",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public @ResponseBody Object add(Emp vo){
        log.info("数据增加成功:"+vo);
        JSONObject js = new JSONObject();
        js.put("flag", true);
        return js;
    }

②、在restful.js中增加:

$(addBut).on("click",function(){
        $.ajax({
            url: "restful",
            type : "post",
            data : {
                empno : 110,
                ename : "RESTful",
                sal : 1.1,
                hiredate : "1111-11-11"
            },
            success : function(data){
                $(showDiv).append("<p> 数据增加成功:"+data.flag+"</p>");
            },
            dataType : "json",
            error : function(data){
                $(showDiv).append("<p>出错了</p>");
            }
        })
    });

2、PUT请求实现数据更新
①、在TextRestful.java中增加:

@RequestMapping(value="/restful",method=RequestMethod.PUT,produces="application/json;charset=UTF-8")
    public @ResponseBody Object edit(Emp vo){
        log.info("数据更新成功:"+vo);
        JSONObject js = new JSONObject();
        js.put("flag", true);
        return js;
    }

②、在restful.js中增加:

$(editBut).on("click",function(){
        $.ajax({
            url: "restful",
            type : "post",
            data : {
                _method : "put",
                empno : 110,
                ename : "RESTful",
                sal : 1.1,
                hiredate : "1111-11-11"
            },
            success : function(data){
                $(showDiv).append("<p> 数据更新成功:"+data.flag+"</p>");
            },
            dataType : "json",
            error : function(data){
                $(showDiv).append("<p>出错了</p>");
            }
        })
    });

3、DELETE请求实现数据删除
①、在TextRestful.java中增加:

@RequestMapping(value="/restful",method=RequestMethod.DELETE,produces="application/json;charset=UTF-8")
    public @ResponseBody Object remove(int mid){
        log.info("要删除的是:"+mid);
        JSONObject js = new JSONObject();
        js.put("flag", true);
        return js;
    }

②、在restful.js中增加:

$(deleteBut).on("click",function(){
        $.ajax({
            url: "restful",
            method : "post" ,
            data : {
                _method : "delete",
                mid : 1
            },
            dataType : "json",
            success : function(data){
                $(showDiv).append("<p> 数据删除成功:"+data.flag+"</p>");
            },
            error : function(data){
                $(showDiv).append("<p>出错了</p>");
            }
        })
    });

4、GET请求实现数据查询
①、在TextRestful.java中增加:

@RequestMapping(value="/restful/{mid:\\d+}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public @ResponseBody Object get(@PathVariable("mid") int mid){
        log.info("要查看的是:"+mid);
        Emp vo = new Emp();
        vo.setEmpno(mid);
        vo.setEname("SMITH");
        vo.setSal(1.1);
        vo.setHiredate(new Date());
        JSONObject js = new JSONObject();
        js.put("emp", vo);
        return js;
    }

②、在restful.js中增加:

$(getBut).on("click",function(){
        $.ajax({
            url: "restful/1",
            method : "get" ,
            data : {
            },
            dataType : "json",
            success : function(data){
                $(showDiv).append("<p> 编号:"+data.allMembers.empno+",名称:"+data.allMembers.ename+",工资"+
                        data.allMembers.sal+",日期:"+data.emp.hiredate+"</p>");
                console.log(1);
            },
            error : function(data){
                $(showDiv).append("<p>出错了</p>");
            }
        })
    });

5、PATCH请求实现数据分页
①、在TextRestful.java中增加:

@RequestMapping(value="/restful/{condition}",method=RequestMethod.PATCH,produces="application/json;charset=UTF-8")
    public @ResponseBody Object list(@PathVariable("condition") String param){
        log.info("查看的是:"+param);
        int currentPage = 4;
        int lineSize = 5;
        List<Emp> all = new ArrayList<Emp>() ;
        for (int x = ((currentPage-1)*lineSize);x< currentPage *lineSize; x ++) {
            Emp vo = new Emp() ;
            vo.setEmpno(x);
            vo.setEname("姓名 - " + x);
            vo.setSal(10000.0 + x);
            vo.setHiredate(new Date());
            all.add(vo) ;
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("allEmps", all);
        return map;
    }

②、在restful.js中增加:

$(listBut).on("click",function(){
        $.ajax({
            url: "restful/1",
            method : "PATCH" ,
            dataType : "json",
            success : function(data){
                for(var t=0;t<data.allEmps.length;t++){
                    $(showDiv).append("<p> 编号:"+data.allEmps[t].empno+",名称:"+data.allEmps[t].ename+",工资"+
                            data.allEmps[t].sal+",日期:"+data.allEmps[x].hiredate+"</p>");
                }
            },
            error : function(data){
                $(showDiv).append("<p>出错了</p>");
            }
        })
    });
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值