SSM虾米音乐项目6--后台专辑模块的修改和删除

删除操作

删除的前端界面

删除的前端代码

复制代码
<button data-toggle="button" class="btn btn-sm btn-warning" aid="${album.aid}" pic="${album.pic}"> 删除 </button></td>

点击删除按钮,会调用JS中的AJAX请求

复制代码
//删除
$(".btn-warning").click(function () {//通过类选择器给删除按钮绑定事件
    var aid = $(this).attr("aid");//获取当前专辑的aid
    var pic = $(this).attr("pic");//获取当前专辑的pic值
    //弹出一个确认对话框,内容为"是否确认删除?"。
    layer.confirm('是否确认删除?', {icon: 3, title:'提示'}, function(index){
        $.ajax({
            url: "/album/delAlbum",//访问后端的delAlum方法
            type: "post",
            data: {
                aid:aid,//将参数传递给后端
                pic:pic
            },
            dataType: "text",
            success: function (text) {
                if (text == "success") {
                    layer.msg("删除成功");
                    layer.close(index);
                    $("#pageNo").val(1);
                    //页面刷新
                    $("#txForm").submit();
                }
            }
        })
    });
});

访问后端的方法,根据传递的aid的值和pic的值进行删除,删除数据库表中的记录以及服务器上传的专辑封面

后端方法实现代码

复制代码
/**
 * 删除对应ID的专辑信息
 * @param aid
 * @return
 */
@ResponseBody
@PostMapping("/delAlbum")
public String delAlbum(Integer aid,String pic){
    System.out.println(pic);
    //删除服务器上的pic  专辑封面
    String pre="(文件服务器的端口)";
    String realPath=pre+pic;
    System.out.println(realPath);
    Client client=Client.create();
    WebResource resource=client.resource(realPath);
    resource.delete();
    //删除数据库中的AID对应的专辑
    albumService.deleteByPrimaryKey(aid);
    return "success";
}

如果删除成功,就像前端传递text文本 "success",前端通过判断,显示"删除成功"

访问数据库的Mapper层 SQL语句

Mapper层代码

复制代码
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
  delete from album
  where AID = #{aid,jdbcType=INTEGER}
</delete>

修改操作

首先要在弹窗中回显该专辑原本的数据,在对内容进行编辑,修改

前端的修改弹窗

修改弹窗对应的实现代码

弹出弹窗的操作

首先通过点击"修改按钮",弹出弹窗

修改按钮

复制代码
<button class="btn btn-sm btn-primary" type="button" modify aid="${album.aid}" > 修改 </button>

通过选择器给按钮绑定事件,发送AJAX请求

复制代码
var pop1;
$("[modify]").click(function () {
    var aid = $(this).attr("aid");
    var address="文件服务器端口";
    $.ajax({
        url: "/album/getAlbum",
        type: "post",
        data: {
            aid:aid
        },
        dataType: "json",
        success: function (jsonObj) {
            $("#aid").val(jsonObj.aid);
            $("#paname").val(jsonObj.aname);
            $("#pcompany").val(jsonObj.company);
            $("#updatePdate").val(jsonObj.pdate);
            $("#plang").val(jsonObj.lang);
            $("#albumImg1").attr("src",address+jsonObj.pic);
            $("#lastImg1").val(address+jsonObj.pic);
            $("#pic1").val(jsonObj.pic);
        }
    })

    pop1 = layer.open({
        type: 1,
        area:[900, 650],
        content: $('#albumPop1')
    });

})

访问后端的getAlum方法,根据前端传递过来的aid信息,查询对应的专辑信息

复制代码
//根据ID查询
@ResponseBody
@PostMapping("/getAlbum")
public Album getMtype(int aid){
    Album album=albumService.selectByPrimaryKey(aid);
    return album;
}

并将数据以json格式返回给前端,进行数据的回显,并且弹出弹窗

进行修改

修改对应的前端代码

复制代码
<%--修改弹窗--%>
<div id="albumPop1" style="margin-right: 50px;margin-top: 50px; display: none">
    <form id="updateAlbumForm" class="layui-form" method="post" action="/album/updateAlbum" enctype="multipart/form-data" lay-filter="example">
        <input type="hidden" name="aid" id="aid">
        <div class="layui-form-item" >
            <label class="layui-form-label" style="width:100px">专辑名字</label>
            <div class="layui-input-block">
                <input id="paname" type="text" name="aname" style="color: black; border-color: lightgray;background-color: white"  lay-verify="paname" autocomplete="off" placeholder="请输入专辑名" class="layui-input">
            </div>
        </div>


        <div class="layui-form-item" >
            <label class="layui-form-label" style="width:100px">发行公司</label>
            <div class="layui-input-block">
                <input id="pcompany" type="text" name="company" style="color: black; border-color: lightgray;background-color: white"  lay-verify="pcompany" autocomplete="off" placeholder="请输入公司名" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item" >
            <label class="layui-form-label" style="width:100px">发行时间</label>
            <div class="layui-input-block">
                <input type="text" id="updatePdate"  name="pdate" style="color: black; border-color: lightgray;background-color: white"  lay-verify="pdate1" autocomplete="off" placeholder="请输入发行时间" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label  class="layui-form-label" style="width:100px">图片</label>
            <div class="controls form-group">
                <div class="col-sm-4 col-md-2">
                    <div class="image-row">
                        <div class="image-set">
                            <a class="example-image-link" href="../../img/gallery-photo/image-3.jpg" data-lightbox="example-set" title="Click on the right side of the image to move forward.">
                                <img id="albumImg1" class="example-image"  src="../../img/gallery-photo/thumb-3.jpg"  alt="Plants: image 1 0f 4 thumb" width="150" height="150" />
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label for="i-file1" class="layui-form-label" style="width:100px">选择文件</label>
            <!--<div class="col-sm-4 control-label">选择文件</div>-->
            <div id="examples1" class="section examples-section">
                <div class="col-sm-6">
                    <div class="input-group">
                        <input id='location1' class="form-control" onclick="$('#i-file1').click();">
                        <label class="input-group-btn">
                            <input  type="button" id="i-check1" value="修改封面" class="btn btn-primary" onclick="$('#i-file1').click();">
                        </label>
                    </div>
                </div>
                <input type="hidden" id="pic1" name="pic" lay-verify="pic1">
                <input type="hidden" id="lastImg1" name="lastImg">
                <input type="file" name="picfile" id='i-file1'  accept=".jpg, .png" onchange="submitFile1()" style="border-color: lightgray;background-color: lightgray;display: none">
            </div>
        </div>

        <div class="layui-form-item" >
            <label for="lang1" class="layui-form-label " style="width:100px">语种</label>
            <div class="layui-input-block">
                <input id="plang"  type="text" name="lang" style="color: black; border-color: lightgray;background-color: white"  lay-verify="plang" autocomplete="off" placeholder="请输入语种" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal layui-btn-radius" lay-submit="" lay-filter="demo2">修改专辑</button>
            </div>
        </div>
    </form>
</div>
重名检查

进行对应的修改时,JS会对修改的内容进行检查

复制代码
form1.verify({
    paname: function(value, item){ //value:表单的值、item:表单的DOM对象
        if(!new RegExp("^[a-zA-Z0-9\u4e00-\u9fa5]{1,20}$").test(value)){
            return '必须是中英文或数字字符,长度1-20';
        }
        var flag = "false";
        var aid=$('#aid').val();
        $.ajax({
            url: "/album/isSameName",
            type: "post",
            data: {
                aname:value,
                aid:aid
            },
            async:false,
            dataType: "text",
            success: function (text) {
                flag = text;
            }
        })
        if(flag == "true"){
            return "专辑名已存在";
        }

    },
    //我们既支持上述函数式的方式,也支持下述数组的形式
    //数组的两个值分别代表:[正则匹配、匹配不符时的提示文字]
    pcompany: [/^[a-zA-Z0-9\u4e00-\u9fa5]{1,20}$/,'必须是中英文或数字字符,长度1-20'],
    pdate1: [/^.+$/,'请选择发现日期'],
    pic1: [/^.+$/,'亲不要忘记上传专辑封面喔'],
    plang: [/^[\u4e00-\u9fa5]{1,10}$/,'请输入中文的语种']
});

注意此时的重名判断,传递两个参数 aid aName,后端应该查询除了本专辑之外,和其他专辑是否重名

是否重名的后端实现代码

复制代码
//判断是否重名
@ResponseBody
@PostMapping("/isSameName")
public String isSameName(String aname,Integer aid){
    Album album=new Album();
    album.setAid(aid);
    album.setAname(aname);
    System.out.println(album);
    Integer count=albumService.isSameName(album);
    if(count==1){
        return "true";
    }else {
        return "false";
    }
}

对应的查询的SQL语句

复制代码
<select id="isSameName" parameterType="com.qcby.model.Album" resultType="java.lang.Integer">
  select
  count(*)
  from album t
  <where>
    <if test="aname != null and aname != ''">
      t.aname=#{aname}
    </if>
    <if test="aid !=null">
      and t.aid!=#{aid}
    </if>
  </where>
</select>

此时一定要有aid!=#{aid]的操作,否则无法顺利进行修改专辑名的操作

文件修改

文件修改,应该判断专辑封面是否被修改,如果修改的话,需要将旧的封面从服务器删除

前端实现代码

复制代码
function  submitFile1(){
    var lastImg=$("#lastImg1").val();
    alert("修改 "+lastImg);
    $("#location1").val($("#i-file1").val());
    $("#updateAlbumForm").ajaxSubmit({
        url:"/upload/uploadFile",
        data:{
            fileType:"pic",
            update:"true"
        },
        dataType:"json",
        success:function (json) {
            $("#albumImg1").attr("src",json.realPath);
            $("#lastImg1").val(json.realPath);
            $("#pic1").val(json.relativePath);
        }
    })
}

后端实现代码

复制代码
@RequestMapping("/uploadFile")
    public void uploadFile(HttpServletRequest request, HttpServletResponse response, MultipartFile picfile, String fileType, String lastImg,String update) throws IOException {

        // 后续现有代码逻辑
        // 1.获取前端传递过来的所有有关于文件上传的参数
        // MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request;

        //2.获取存储文件的相关内容
        // Map<String,MultipartFile> fileMap=mr.getFileMap();

        //3.获取文件
//        MultipartFile file=fileMap.get("picfile");

        //4.获取该文件的字节数组 方便上传
        byte[] bytes=picfile.getBytes();

        //5.获取文件名称
        String originalFilename=picfile.getOriginalFilename();
        //vhjbh.jpg
        //6.获取文件名的后缀 产生新的名字  .jpg(.exe)
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));

        //7.定义一个新的名字  abscjsdc.jpg
        String fileName= UUID.randomUUID().toString();
        fileName=fileName+suffix;

        //8.上传  获取文件的上传位置  图片服务器的位置 
        String filePath="文件服务器的端口";
        //绝对路径 
        String realPath=filePath+"/"+fileType+"/"+fileName;
        //相对路径 /pic/05.jpg
        String relativePath="/"+fileType+"/"+fileName;
        //9.jersy客户端进行上传
        Client client= Client.create();

        //判断是否为修改换封面
        if(update.equals("false")){
            if(lastImg!=null&&!"".equals(lastImg)){
                WebResource resource=client.resource(lastImg);
                resource.delete();
            }
        }
        //10.获取web资源
        WebResource resource=client.resource(realPath);
        //11.上传
        resource.put(bytes);
        //返回前端进行页面渲染
        JSONObject jo=new JSONObject();
        jo.put("realPath",realPath);
        jo.put("relativePath",relativePath);
        //响应对象的原始方式返回
        response.getWriter().write(jo.toString());

    }
修改操作的实现

通过提交form表单的形式实现修改操作

复制代码
var form1 = layui.form;
//监听提交
form1.on('submit(demo2)', function (data) {
    //layer.msg(JSON.stringify(data.field));
    $.ajax({
        url: "/album/updateAlbum",
        type: "post",
        data: data.field,
        dataType: "text",
        success: function (text) {
            if (text == "success") {
                layer.msg("修改成功");
                layer.close(pop1);
                $("#pageNo").val(1);
                //页面刷新
                $("#txForm").submit();
            }
        }
    });

    return false;
});

后端实现修改

复制代码
//修改专辑信息
@ResponseBody
@PostMapping("/updateAlbum")
public String updateAlbum(Album al){
    albumService.updateByPrimaryKeySelective(al);
    return "success";
}

实现修改的Mapper层动态SQL语句

复制代码
<update id="updateByPrimaryKeySelective" parameterType="com.qcby.model.Album">
  update album
  <set>
    <if test="aname != null">
      ANAME = #{aname,jdbcType=VARCHAR},
    </if>
    <if test="pic != null">
      PIC = #{pic,jdbcType=VARCHAR},
    </if>
    <if test="company != null">
      COMPANY = #{company,jdbcType=VARCHAR},
    </if>
    <if test="pdate != null">
      PDATE = #{pdate,jdbcType=DATE},
    </if>
    <if test="lang != null">
      LANG = #{lang,jdbcType=VARCHAR},
    </if>
  </set>
  where AID = #{aid,jdbcType=INTEGER}
</update>

修改操作实现之后,需要刷新界面,重新提交一下查询的表单

相关推荐
Jeled1 天前
Retrofit 与 OkHttp 全面解析与实战使用(含封装示例)
android·okhttp·android studio·retrofit
Jeled2 天前
Android 网络层最佳实践:Retrofit + OkHttp 封装与实战
android·okhttp·kotlin·android studio·retrofit
allk555 天前
OkHttp源码解析(一)
android·okhttp
allk555 天前
OkHttp源码解析(二)
android·okhttp
aFakeProgramer5 天前
拆分PDF.html 办公小工具
okhttp
一壶浊酒..6 天前
ajax局部更新
前端·ajax·okhttp
洛克大航海9 天前
Ajax基本使用
java·javascript·ajax·okhttp
whltaoin15 天前
Java 网络请求 Jar 包选型指南:从基础到实战
java·http·okhttp·网络请求·retrofit
华农第一蒟蒻16 天前
谈谈跨域问题
java·后端·nginx·安全·okhttp·c5全栈
一直向钱18 天前
android 基于okhttp的socket封装
android·okhttp