RestfulCRUD(实现增删改查,图片上传回显,批量删除)

自己学习过程中的一个记录,通过restful风格,对数据进行增删改查;
而我还同时实现了数据的批量删除;当然,单个删除的方法是没有写的;
具体的代码基本上都有,只是一个初学者,如有不妥的地方,请多多指教;

数据表:(随便创建的)

    private Integer id;
    private String item;
    private String times;
    private String pic;
    private Date createtime;

Mapper接口

    List<Vote> selAll();//查询所有
    Vote selOne(Integer id);//查询单个
    void delList(Integer id);//批量删除
    void updVote(Vote vote); //修改
    void addVote(Vote vote); //添加

mapper.xml

<!--查询所有的-->
    <select id="selAll" resultType="Vote">
        SELECT * FROM vote
    </select>
    <!--查询单个-->
    <select id="selOne" parameterType="Integer" resultType="Vote">
        SELECT * FROM vote WHERE id = #{id}
    </select>
    <!--删除-->
    <delete id="delList" parameterType="Integer">
        DELETE FROM vote WHERE id = #{id}
    </delete>
    <!--修改-->
    <update id="updVote" parameterType="Vote">
        UPDATE vote SET pic = #{pic},item = #{item},times = #{times},createtime = #{createtime}
        WHERE id = #{id}
    </update>
    <!--添加-->
    <insert id="addVote" parameterType="vote">
        INSERT INTO vote(item,times,pic,createtime)
        VALUES (#{item},#{times},#{pic},#{createtime})
    </insert>

service

    List<Vote> selAll();//查询所有
    Vote selOne(Integer id); //查询单个
    boolean delList(int[] id); //批量删除
    void updVote(Vote vote);//修改
    void addVote(Vote vote);//添加

serviceImpl

	@Autowired
    private VoteMapper voteMapper;
    @Override
    public List<Vote> selAll() {
        return voteMapper.selAll();
    }
    @Override
    public Vote selOne(Integer id) {
        return voteMapper.selOne(id);
    }
    @Override
    public boolean delList(int[] id) {
        boolean bl = true;
        try {
            for (Integer i: id
                 ) {
                voteMapper.delList(i);
            }
        } catch (Exception e) {
            bl = false;
            e.printStackTrace();
        }
        return bl;
    }
    @Override
    public void updVote(Vote vote) {
        voteMapper.updVote(vote);
    }
    @Override
    public void addVote(Vote vote) {
        voteMapper.addVote(vote);

    }

Controller层

 @Autowired
    private VoteService voteService;
    /**
     * 查询所有
     * @param model
     * @return
     */
    @GetMapping("/vote")
    public String selAll(Model model){
        List<Vote> votes = voteService.selAll();
        model.addAttribute("votes",votes);
        return "home";
    }
    /**
     * 跳转到修改界面,并且将查出来的值传输到修改界面;
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/vote/{id}")
    public String selOne(@PathVariable("id") Integer id, Model model){
        Vote vote = voteService.selOne(id);
        model.addAttribute("onevote",vote);
        return "upd";
    }
    /**
     * 修改员工的方法
     * @param vote
     * @return
     */
    @PutMapping("/vote")
    public String updVotes(Vote vote){
        voteService.updVote(vote);
        System.out.println("修改方法");
        return "redirect:/vote";
    }
    /**
     * 批量删除方法
     * @param id
     * @param response
     * @throws Exception
     */
    @DeleteMapping(name = "/vote")
    public void delVotes(@RequestParam("id[]") int[] id,HttpServletResponse response) throws Exception{
        System.out.println();
        for (Integer i:id
             ) {
            System.out.println(i);
        }
        voteService.delList(id);
        PrintWriter out = response.getWriter();
        List<Vote> votes = voteService.selAll();
        response.setCharacterEncoding("utf-8");
        String json = JSON.toJSONStringWithDateFormat(votes,"yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        out.print(json);

    }
    /**
     * 使用Restful
     * 添加vote方法
     * @param vote
     * @return
     */
   @PostMapping("/vote")
    public String addVote(Vote vote){
        voteService.addVote(vote);

        return "redirect:/vote";


    }

    @RequestMapping("/doUpload")
    @ResponseBody
    public void doUpload(MultipartFile photo, HttpServletResponse resp, Model model) throws IOException {
        Map<String,String> result = new HashMap<String,String>();
        resp.setContentType("application/json;utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //第一步先判断是否为空
        if(null == photo){
            result.put("type","error");
            result.put("msg","请选择需要上传的图片");
            out.print(JSON.toJSONString(result));
            return;
        }
        //第二步判断文件的大小
        long sizeNum = photo.getSize();
        if(sizeNum>1024*1024*10){
            result.put("type","error");
            result.put("msg","上传文件的大小不能超过10M");
            out.print(JSON.toJSONString(result));
            return;
        }
        //第三步获取文件的后缀给文件改写名字
        int index = photo.getOriginalFilename().lastIndexOf(".");
        String suffix = photo.getOriginalFilename().substring(index);
        if (!".jpg,.jpeg,.gif,.png".toUpperCase().contains(suffix.toUpperCase())) {
            result.put("type", "error");
            result.put("msg", "请选择jpg,jpeg,gif,png格式的图片!");
            out.print(JSON.toJSONString(result));
            return;
        }
        //新的文件名字
        String fileName = System.currentTimeMillis()+""+suffix;
        //产生一个新的图片文件,把它写入到磁盘
        File filepic = new File(this.REAL_PATH,fileName);
        try {
            photo.transferTo(filepic);
        } catch (IOException e) {
            result.put("type","error");
            result.put("msg","保存文件异常");
            e.printStackTrace();
            out.print(JSON.toJSONString(result));
            return;
        }
        //第四步返回回去
        result.put("type", "success");
        result.put("msg", "保存成功");
        result.put("filepath",this.VISIT_PATH);
        result.put("fileName",fileName);
        out.print(JSON.toJSONString(result));
        model.addAttribute("fileName",fileName);
        return;
    }

工具类(使controller来继承这个工具类;实现时间的转换,以及图片的上传,以及路径的读取)

public class Utils extends DateUtils {
     // 设置上传图片的路径
    public final String REAL_PATH = "D:"+ File.separator+"File"+File.separator+"AAA_JAVA_STUDAY"+File.separator+"picture"+File.separator;
     //读取图片
    public final String VISIT_PATH = File.separator+"pic"+File.separator;

     //将前台传递过来的日期格式的字符串,自动转化为Date类型

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
     //* 日期型字符串转化为日期 格式

    public static Date parseDate(Object str) {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(parseDate(text));
            }
        });
    }
}

jsp主界面(查询出来的数据,将数据)

<button type="button" class="btn-primary" id="del">
        批量删除
    </button>
    <table class="table">
        <caption>基本的表格布局</caption>
        <thead>
        <tr>
            <th><input type="checkbox" name="all" id="all"></th>
            <th>序号</th>
            <th>列1</th>
            <th>列2</th>
            <th>图片</th>
            <th>时间</th>
        </tr>
        </thead>
        <tbody id="tbody">
        <c:forEach items="${votes}" var="s" varStatus="sd">
            <tr>
                <td>
                    <input type="checkbox" name="id" value="${s.id}" class="id">
                </td>
                <td>${sd.count}</td>
                <td>${s.item}</td>
                <td>${s.times}</td>
                <td>
                    <img src="${path}/pic/${s.pic}" width="60px" height="60px" class="img-circle">
                </td>
                <td>
                    <fmt:formatDate value="${s.createtime}" pattern="yyyy-MM-dd hh:mm:ss"></fmt:formatDate>
                </td>
                <td>
                    <a href="${path}/vote/${s.id}">修改</a>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>

批量删除的方式,使用ajax实现调用后controller的@DeleteMapping(name = “/vote”)方法

<script type="text/javascript">
    /*实现全选*/
    $("#all").click(function (){
        if (this.checked){
            $(":checkbox[name='id']").prop("checked",true);
        }else{
            $(":checkbox[name='id']").prop("checked",false);
        }
    })
    $(":checkbox[name='id']").bind("click",function (){
        num = $(":checkbox[name='id']").length;
        nums = $(":checkbox[name='id']:checked").length;
        if (num == nums){
            $("#all").prop("checked",true);
        }else {
            $("#all").prop("checked",false);
        }
    })
    /*批量删除*/
    $("#del").bind("click",function (){
        var ids = new Array();
        num =  $(":checkbox[name='id']:checked").length;
        if (num==0){
            alert("选择");
            return ;
        }
        $.each($(":checkbox[name='id']:checked"),function (i,v){
            ids[i] = this.value;
        })
        alert(ids)
        $.ajax({
            url:"${path}/vote",
            type:"post",
            dataType:"json",
            data: {
                _method:"delete",
                id:ids
            },
            success:function (res){
                $("#tbody").html("");
                $.each(res,function (i,v){
                    $("#tbody").append(" <tr>" +
                        "                <td>" +
                        "                    <input type='checkbox' name='id' value='"+v.id+"' class='id'>" +
                        "                </td>" +
                        "                <td>"+i+"</td>" +
                        "                <td>"+v.item+"</td>" +
                        "                <td>"+v.times+"</td>" +
                        "                <td>" +
                        "                    <img src='${path}/pic/"+v.pic+"' width='60px' height='60px' class='img-circle'>\n" +
                        "                </td>" +
                        "                <td>" +v.createtime+
                        "                </td>" +
                        "                <td>" +
                        "                    <a href='${path}/vote/"+v.id+"'>修改</a>" +
                        "                </td>" +
                        "            </tr>")
                }
                )
            }
        })
    })

图片的上传回显html代码块(第一个“上传”是将图片上传到指定路径,第二个“提交是将图片的名字储存到数据库中”)

<form method="post" action="/vote">
<div class="form-group">
                        <label for="item">名称1</label>
                        <input type="text" class="form-control" id="item" name="item"
                               placeholder="请输入名称">
                    </div>
                    <div class="form-group">
                        <label for="times">名称2</label>
                        <input type="text" class="form-control" id="times" name="times"
                               placeholder="请输入名称">
                    </div>
                    <div class="form-group">
                        <label for="createtime">时间</label>
                        <input type="text" class="form-control" id="createtime" name="createtime"
                               placeholder="请输入名称">
                    </div>
                    <div class="form-group">
                        <label for="inputfile">文件输入</label>
                        <input type="hidden" value="" id="pic" name="pic">
                        <input type="file" id="inputfile">
                    </div>
                    <img width="60px" height="60px" alt="选择图片" id="imgs" class="img-circle">
                    <div class="checkbox">
                        <input type="button" class="btn-primary" value="上传" id="btn_sub">
                    </div>
                    <button type="submit" class="btn btn-primary">
                        提交更改
                    </button>
</form>

上传回显的jq代码

 $(function (){
        $("#btn_sub").click(function (){
            if ($("#inputfile").val()==""){
                alert("请选择文件!!!")
                return ;
            }

            let fmt = new FormData();
            fmt.append("photo",document.getElementById("inputfile").files[0]);

            $.ajax({
                url:"doUpload",
                data:fmt,
                type:"POST",
                contentType:false,
                processData:false,
                success:function (data){
                    if (data.type == "success"){
                        $("#pic").val(data.fileName);
                        $("#imgs").attr("src", data.filepath+data.fileName);
                    }else {
                        alert(data.msg)
                    }
                },
                error:function (res){
                    alert("上传失败!!!")
                }

            })
        })

    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码不能跑我能跑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值