springmvcREST风格

JsonResult

package com.sy.dto;

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonResult {
    private Integer code;
    private String error;
    private Object data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "JsonResult{" +
                "code=" + code +
                ", error='" + error + '\'' +
                ", data=" + data +
                '}';
    }
}

package com.sy.controller;

import com.sy.dto.JsonResult;
import com.sy.entity.Dept;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新建部门信息
     */
    @RequestMapping(value = "depts", method = RequestMethod.POST)
    public JsonResult addDept(HttpServletResponse res, String dname, String loc) {
        JsonResult jsonResult = new JsonResult();
        try {
            //注意:前端和后端一般需要进行相同逻辑的校验
            //400
            //部门名称不能为空
            if (StringUtils.isBlank(dname)) {
                jsonResult.setCode(400);
                res.setStatus(400);
                jsonResult.setError("部门名称不能为空");
                return jsonResult;
            }
            //部门所在地不能为空
            if (StringUtils.isBlank(loc)) {
                jsonResult.setCode(400);
                res.setStatus(400);
                jsonResult.setError("部门所在地不能为空");
                return jsonResult;
            }
            //部门名称不能相同
            //a.查询所有已有的部门名称
            List<String> dnames = jdbcTemplate.queryForList("select dname from dept", String.class);
            //b.判断传入的部门名是否在这个集合中
            if (dnames.contains(dname)) {
                jsonResult.setCode(400);
                res.setStatus(400);
                jsonResult.setError("部门名称:" + dname + "已经存在");
                return jsonResult;
            }
            // 201
            //返回新创建的数据
            GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
            jdbcTemplate.update((con) -> {
                PreparedStatement ps = con.prepareStatement("insert into dept(dname,loc) values(?,?)", new String[]{"deptno"});
                ps.setString(1, dname);
                ps.setString(2, loc);
                return ps;
            }, keyHolder);
            //获取自增主键的值
            int deptno = keyHolder.getKey().intValue();
            //构建要返回的部门对象
            Dept dept = new Dept();
            dept.setDeptno(deptno);
            dept.setDname(dname);
            dept.setLoc(loc);
            jsonResult.setCode(201);
            res.setStatus(201);
            jsonResult.setData(dept);
            return jsonResult;

        } catch (Exception e) {
            //500
            //服务端异常
            jsonResult.setCode(500);
            res.setStatus(500);
            jsonResult.setError("服务端异常");
            e.printStackTrace();
            return jsonResult;
        }


    }
}

package com.sy.controller;

import com.sun.org.apache.xml.internal.serializer.Method;
import com.sy.dto.JsonResult;
import com.sy.dto.Result;
import com.sy.entity.Emp;
import com.sy.vo.EmpUpdateVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Spring4.0后出现的注解,相当于将@Controller和@ResponseBody进行了组合
 * 对于控制器中所有的方法,相当于默认都添加了@ResponseBody注解
 * 方便实现RESTful风格的数据接口
 */
@RestController
public class EmpController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询所有的员工信息
     */
    @RequestMapping(value = "emps", method = RequestMethod.GET)
    public JsonResult getAllEmps(HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            List<Emp> emps = jdbcTemplate.query("select * from emp", new BeanPropertyRowMapper<>(Emp.class));
            //有可能查不到数据:404
            if (CollectionUtils.isEmpty(emps)) {
                result.setCode(404);
                res.setStatus(404);
                result.setError("没有找到任何数据");
                return result;
            }
            result.setCode(200);
            result.setData(emps);
            return result;
        } catch (Exception e) {
            //有可能出现服务端异常:500
            result.setCode(500);
            res.setStatus(500);
            result.setError("服务器异常");
            e.printStackTrace();
            return result;
        }

    }

    /**
     * 根据员工编号查询员工信息
     * <p>
     * 注解@PathVariable用来映射路径中出现的参数,并非在?后面出现的参数值
     */
    @RequestMapping(value = "emps/{empno}", method = RequestMethod.GET)
    public JsonResult getEmpById(@PathVariable("empno") Integer empno, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            List<Emp> emps = jdbcTemplate.query("select * from emp where empno=?", new BeanPropertyRowMapper<>(Emp.class), empno);
            //有可能查不到数据:404
            if (CollectionUtils.isEmpty(emps)) {
                result.setCode(404);
                res.setStatus(404);
                result.setError("没有找到任何数据");
                return result;
            }
            result.setCode(200);
            result.setData(emps.get(0));
            return result;
        } catch (Exception e) {
            //有可能出现服务端异常:500
            result.setCode(500);
            res.setStatus(500);
            result.setError("服务器异常");
            e.printStackTrace();
            return result;
        }
    }

    /**
     * 获取指定部门编号中指定编号的员工信息
     */
    @RequestMapping(value = "depts/{deptno}/emps/{empno}", method = RequestMethod.GET)
    public JsonResult getEmpByDeptNoAndEmpno(HttpServletResponse res, @PathVariable("deptno") Integer deptno, @PathVariable("empno") Integer empno) {
        JsonResult result = new JsonResult();
        try {
            List<Emp> emps = jdbcTemplate.query("select * from emp where deptno=? and empno=?", new BeanPropertyRowMapper<>(Emp.class), deptno, empno);
            //有可能查不到数据:404
            if (CollectionUtils.isEmpty(emps)) {
                result.setCode(404);
                res.setStatus(404);
                result.setError("没有找到任何数据");
                return result;
            }
            result.setCode(200);
            result.setData(emps.get(0));
            return result;
        } catch (Exception e) {
            //有可能出现服务端异常:500
            result.setCode(500);
            res.setStatus(500);
            result.setError("服务器异常");
            e.printStackTrace();
            return result;
        }

    }

    /**
     * 根据指定部门员工的薪水的指定顺序查询所有员工信息
     * depts/10/emps?sortby=sal&order=asc
     * depts/10/emps?sortby=sal&order=desc
     * depts/10/emps?sortby=sal&order=ASC
     * depts/10/emps?sortby=sal&order=DESC
     * depts/10/emps?sortby=sal&order=xxx
     */
    @RequestMapping(value = "depts/{deptno}/emps", method = RequestMethod.GET)
    public JsonResult getEmpsByDeptAndSalOrder(HttpServletResponse res, @PathVariable("deptno") Integer deptno, String order) {
        JsonResult result = new JsonResult();
        try {
            //校验排序规则
            if (!Arrays.asList("ASC", "DESC").contains(order.toUpperCase())) {
                result.setCode(400);
                res.setStatus(400);
                result.setError("非法的排序规则,排序规则必须为asc或desc(不区分大小写)");
                return result;
            }
            List<Emp> emps = jdbcTemplate.query("select * from emp where deptno=? order by sal " + order, new BeanPropertyRowMapper<>(Emp.class), deptno);
            //有可能查不到数据:404
            if (CollectionUtils.isEmpty(emps)) {
                result.setCode(404);
                res.setStatus(404);
                result.setError("没有找到任何数据");
                return result;
            }
            result.setCode(200);
            result.setData(emps);
            return result;
        } catch (Exception e) {
            //有可能出现服务端异常:500
            result.setCode(500);
            res.setStatus(500);
            result.setError("服务器异常");
            e.printStackTrace();
            return result;
        }
    }

    /**
     * 根据编号删除员工信息
     */
    @RequestMapping(value = "emps/{empno}", method = RequestMethod.DELETE)
    public JsonResult deleteEmpById(@PathVariable("empno") Integer empno, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            //404
            // 如果要删除的数据不存在

            //204
            //删除成功
            int r = jdbcTemplate.update("delete from emp where empno=?", empno);
            if (r > 0) {
                result.setCode(204);
                res.setStatus(204);
                return result;
            } else {
                result.setCode(404);
                res.setStatus(404);
                result.setError("要删除的数据不存在");
                return result;
            }


        } catch (Exception e) {
            //有可能出现服务端异常:500
            result.setCode(500);
            res.setStatus(500);
            result.setError("服务器异常");
            e.printStackTrace();
            return result;
        }


    }

    /**
     * 更新员工的职位和薪水
     */
    @RequestMapping(value = "emps/{empno}", method = RequestMethod.PUT)
    public JsonResult updateEmpInfo(HttpServletResponse res, @PathVariable("empno") Integer empno, @RequestBody EmpUpdateVo empUpdateVo) {
        String job = empUpdateVo.getJob();
        Double sal = empUpdateVo.getSal();
        System.out.println(empno);
        System.out.println(job);
        System.out.println(sal);

        JsonResult result = new JsonResult();
        try {
            //400
            //职位不能为空
            if (StringUtils.isBlank(job)) {
                result.setCode(400);
                res.setStatus(400);
                result.setError("职位不能为空");
                return result;
            }
            //薪水不得小于0
            if (sal == null) {
                result.setCode(400);
                res.setStatus(400);
                result.setError("薪水不能为空");
                return result;
            }
            if (sal <= 0) {
                result.setCode(400);
                res.setStatus(400);
                result.setError("薪水必须大于0");
                return result;
            }

            //404
            //要更新的员工不存在

            //200
            //返回更新后的完整的员工信息
            int r = jdbcTemplate.update("update emp set job=?,sal=? where empno=?", job, sal, empno);
            if (r > 0) {
                result.setCode(200);
                res.setStatus(200);
                result.setData(jdbcTemplate.queryForObject("select * from emp where empno=?", new BeanPropertyRowMapper<>(Emp.class), empno));
                return result;
            } else {
                result.setCode(404);
                res.setStatus(404);
                result.setError("要更新的数据不存在");
                return result;
            }

        } catch (Exception e) {
            //500
            //服务端异常
            result.setCode(500);
            res.setStatus(500);
            result.setError("服务器异常");
            e.printStackTrace();
            return result;
        }

    }

}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" onclick="get1()" value="GET1">
<input type="button" onclick="get2()" value="GET2">
<input type="button" onclick="get3()" value="GET3">
<input type="button" onclick="get4()" value="GET4">
<input type="button" onclick="post()" value="POST">
<input type="button" onclick="del()" value="DELETE">
<input type="button" onclick="put()" value="PUT">


<form action="http://localhost:8888/v1.0/emps/7369" method="post">
    <input type="hidden" name="_method" value="delete"/>
    <button>提交</button>
</form>

</body>
<script type="text/javascript" src="js/jquery1.9.1.js"></script>
<script>
    var serverPath = "http://localhost:8888/v1.0/";

    function get1() {
        $.ajax({
            type: "GET",
            url: serverPath + "emps",
            success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }

    function get2() {
        $.ajax({
            type: "GET",
            url: serverPath + "emps/7369",
            success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }

    function get3() {
        $.ajax({
            type: "GET",
            url: serverPath + "depts/44/emps/7369",
            success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }


    function get4() {
        $.ajax({
            type: "GET",
            url: serverPath + "depts/20/emps?sortby=sal&order=ZZZ",
            success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }

    function post() {
        $.ajax({
            type: "POST",
            url: serverPath + "depts",
            data: {
                dname: ".NET",
                loc: "sh"
            },
            success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }

    function del() {
        $.ajax({
            type: "DELETE",
            url: serverPath + "emps/7876",
            success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }

    function put() {
        $.ajax({
            type: "PUT",
            url: serverPath + "emps/7369",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify({
                job: "Java",
                sal: 0
            }), success: function (data) {
                console.log(data);
            }, error: function (res) {
                console.log(JSON.parse(res.responseText).error);
            }
        });
    }
</script>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值