我是靠谱客的博主 俭朴红酒,最近开发中收集的这篇文章主要介绍多层级标签的提交,利用jquery拼接json,后台转java对象,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

这两天周末加班把复杂的多层级的标签功能实现了一下,算是遇到的最难的一个功能了,前台jsp页面利用jquery拼接数组,后台转换成json,然后再转java对象,主要是多层级的。看一下前端页面图

这里写图片描述

1.首先理解一下这个标签的层级关系
总类目–>二级类目–>一级标签–>二级标签;
总共是四层目录级别。前台进行遍历展现是很容易的,但是在添加的时候是非常的苦难的。

2.js代码:在jquery拼接数组的时候使用了k(name),v(value)进行拼接的,在后台转换成json字符串

//新增标签类目
function addProduceTagAndTagType(){

var num = 0;
var numSb = 0;

var totalArry = [];
var bigArry;
var smallArry;
$(".ioo").each(function(){
    bigArry = [];
    var parentTagName = $("input[name='parentTagName']").eq(num).attr('name')+'"'+":"+'"'+$("input[name='parentTagName']").eq(num).val();
    var parentId = $("input[name='parentId']").eq(num).attr('name')+'":"'+$("input[name='parentId']").eq(num).val();
    var parentTagStatus = $("input[name='parentTagStatus']").eq(num).attr('name')+'":"'+$("input[name='parentTagStatus']").eq(num).val();
    var originalTag = $("input[name='originalTag']").eq(num).attr('name')+'":"'+$("input[name='originalTag']").eq(num).val()+'","tags" :<';
    bigArry.push(parentTagName);
    bigArry.push(parentId);
    bigArry.push(parentTagStatus);
    bigArry.push(originalTag);
    $(this).children(".labelSecond").each(function(){
        smallArry = [];
        var childTagName = $("input[name='childTagName']").eq(numSb).attr('name')+'":"'+$("input[name='childTagName']").eq(numSb).val();
        var childId = $("input[name='childId']").eq(numSb).attr('name')+'":"'+$("input[name='childId']").eq(numSb).val();
        var childTagStatus = $("input[name='childTagStatus']").eq(numSb).attr('name')+'":"'+$("input[name='childTagStatus']").eq(numSb).val();
        smallArry.push(childTagName);
        smallArry.push(childId);
        smallArry.push(childTagStatus);
        numSb++;
        bigArry.push(smallArry);
    });
    bigArry.push('>');

    num ++;
    totalArry.push(bigArry)
});
/*console.log($('#tagTypeId').val())
console.log($('#tagTypeStatus').val())
console.log($('#isMultiple').val())*/
console.log(JSON.stringify(totalArry))

//console.log($("input[name='tagTypeStatus']:checked").val())
//进行提交
$.ajax({
    type : "POST",
    url : "add_tagtype_and_tags",
    traditional : true,
    async : false,
    //contentType: 'application/json; charset=utf-8',
    dataType : 'json', 
    data : {

        totalArray : JSON.stringify(totalArry),
        tagTypeId : $('#newTagTypeId').val(),
        tagTypeStatus : $("input[name='newTagTypeStatus']:checked").val(),
        isMultiple : $("input[name='newIsMultiple']:checked").val(),
        tagTypeName : $('#newTagTypeName').val(),
        superTagType : $('#superTagType').val(),
        originalTagType : $('#newOriginalTagType').val()

        },
    success : function(data){
        console.log(data);
        if(data.data == 200){

            window.location.reload();
        }
    }

});
}

2.首先看一下需要转成的java对象:

package com.sc.tradmaster.service.tagService.impl.dto;

import java.util.List;
import java.util.Map;

public class MyParentTag {

    private static final long serialVersionUID = 1L;

    public Integer parentId;

    //父标签的名称
    private String parentTagName;

    //父标签的状态:0删除 1正常
    private Integer parentTagStatus;

    private Integer originalTag;

    private List<MyChildTag> tags;





    public MyParentTag() {
        super();
    }

    public MyParentTag(Integer parentId, String parentTagName, Integer parentTagStatus, Integer originalTag,
            List<MyChildTag> tags) {
        super();
        this.parentId = parentId;
        this.parentTagName = parentTagName;
        this.parentTagStatus = parentTagStatus;
        this.originalTag = originalTag;
        this.tags = tags;
    }

    public String getParentTagName() {
        return parentTagName;
    }

    public void setParentTagName(String parentTagName) {
        this.parentTagName = parentTagName;
    }



    public Integer getParentTagStatus() {
        return parentTagStatus;
    }

    public void setParentTagStatus(Integer parentTagStatus) {
        this.parentTagStatus = parentTagStatus;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }









    public List<MyChildTag> getTags() {
        return tags;
    }

    public void setTags(List<MyChildTag> tags) {
        this.tags = tags;
    }

    public Integer getOriginalTag() {
        return originalTag;
    }

    public void setOriginalTag(Integer originalTag) {
        this.originalTag = originalTag;
    }

    @Override
    public String toString() {
        return "MyParentTag [parentId=" + parentId + ", parentTagName=" + parentTagName + ", parentTagStatus="
                + parentTagStatus + ", originalTag=" + originalTag + ", tags=" + tags + "]";
    }





}


package com.sc.tradmaster.service.tagService.impl.dto;

public class MyChildTag {

    private static final long serialVersionUID = 1L;

    private Integer childId;

    //子标签名称
    private String childTagName;

    //子标签的状态:0删除 1正常
    private Integer childTagStatus;





    public MyChildTag() {
        super();
    }

    public MyChildTag(Integer childId, String childTagName, Integer childTagStatus) {
        super();
        this.childId = childId;
        this.childTagName = childTagName;
        this.childTagStatus = childTagStatus;
    }

    public String getChildTagName() {
        return childTagName;
    }

    public void setChildTagName(String childTagName) {
        this.childTagName = childTagName;
    }

    public Integer getChildTagStatus() {
        return childTagStatus;
    }

    public void setChildTagStatus(Integer childTagStatus) {
        this.childTagStatus = childTagStatus;
    }

    public Integer getChildId() {
        return childId;
    }

    public void setChildId(Integer childId) {
        this.childId = childId;
    }


    @Override
    public String toString() {
        return "MyChildTag [childId=" + childId + ", childTagName=" + childTagName + ", childTagStatus="
                + childTagStatus + "]";
    }


}

3.后台代码

/**
     * 
     * ajax异步添加标签和标签类目 (产品标签和用户标签都可以使用)
     * @param obj   json对象
     * @param tagType
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/add_tagtype_and_tags")
    public Map<String, Object> addProductOrCustomerTagTypeAndTags(String totalArray, Integer tagTypeId, Integer tagTypeStatus, Integer isMultiple, String tagTypeName, Integer superTagType, Integer originalTagType){
        //第一个输出
        System.out.println(totalArray);
        //这里是将前台的数组利用符号的替换组装成json字符串
        String jsonStr = totalArray.replace("\", "");
        String jsonStr1 = jsonStr.replace("[", "{");
        String jsonStr2 = jsonStr1.replace("]", "}");
        String jsonStr3 = jsonStr2.replace("<",", "[");
        String jsonStr4 = jsonStr3.replace(",">"", "]");
         jsonStr4 = jsonStr3.replace("">"", "]");
         jsonStr4 = jsonStr4.replace(",]", "]");
         jsonStr4 = jsonStr4.replace("t", "");
        String jsonStr5 = jsonStr4.substring(1, jsonStr4.length()-1);

        //第二个输出
        System.out.println(jsonStr5);

        Map<String, Object> map = new HashMap<>();

        JSONArray obj = new JSONArray().fromObject("["+jsonStr5+"]");


        List<MyParentTag> list = new ArrayList<>();
        for(int i =0; i<obj.size(); i++){
            JSONObject jObj =  obj.getJSONObject(i);
            //如果这个java对象中还有一个list<Object>这种类型的结构那么就需要进行以下三个操作:
            Map classMap = new HashMap();
            classMap.put("tags", MyChildTag.class);
            MyParentTag my = (MyParentTag) jObj.toBean(jObj, MyParentTag.class, classMap);

            //第三个输出:
            System.out.println(my);
            list.add(my);
        }

            TagType tagType = new TagType();
            tagType.setTagTypeId(tagTypeId);
            tagType.setIsMultiple(isMultiple);
            tagType.setTagTypeStatus(tagTypeStatus);
            tagType.setTagTypeName(tagTypeName);
            tagType.setParentTagTypeId(superTagType);
            tagType.setOriginalTagType(originalTagType);

        User user = (User) this.request.getSession().getAttribute("userInfo");

        Project pro = projectService.findProjectById(user.getParentId());

        boolean flag = tagService.addBatchTagsAndSetTagTypeStatus(pro.getProjectId(), tagType, list);

        if(flag){
            map.put("data", 200);
            map.put("message", "添加成功");
        }else{
            map.put("data", 202);
            map.put("message", "保存失败");
        }

        return map;
    }

打印输出:

//第一个输出:
[["parentTagName":"高","parentId":"211","parentTagStatus":"1","originalTag":"0","tags" :<",">"],["parentTagName":"","parentId":"212","parentTagStatus":"1","originalTag":"0","tags" :<",">"],["parentTagName":"低","parentId":"213","parentTagStatus":"1","originalTag":"0","tags" :<",">"],["parentTagName":"未知","parentId":"214","parentTagStatus":"1","originalTag":"0","tags" :<",">"]]

//第二个输出:
{"parentTagName":"高","parentId":"211","parentTagStatus":"1","originalTag":"0","tags" :[]},{"parentTagName":"中","parentId":"212","parentTagStatus":"1","originalTag":"0","tags" :[]},{"parentTagName":"低","parentId":"213","parentTagStatus":"1","originalTag":"0","tags" :[]},{"parentTagName":"未知","parentId":"214","parentTagStatus":"1","originalTag":"0","tags" :[]}
//第三个输出:
MyParentTag [parentId=211, parentTagName=高, parentTagStatus=1, originalTag=0, tags=[]]
MyParentTag [parentId=212, parentTagName=中, parentTagStatus=1, originalTag=0, tags=[]]
MyParentTag [parentId=213, parentTagName=低, parentTagStatus=1, originalTag=0, tags=[]]
MyParentTag [parentId=214, parentTagName=未知, parentTagStatus=1, originalTag=0, tags=[]]

到这里成功转成了java对象了。

4.再看看service层是如何实现的:因为新建的标签是没有id的,所以需要一层一层的进行保存操作,然后查询出来在给子标签的parentId赋值;

    @Override
    public boolean addBatchTagsAndSetTagTypeStatus(String targetId, TagType tagType, List<MyParentTag> tags) {

        if(StringUtils.isEmpty(targetId))
            return false;
        if(tagType == null)
            return false;

        try {

            //1.保存产品类目下的标签类目
            tagType.setProjectId(targetId);
            if(tagType.getTagTypeId() == null) //如果是已经存在的只保存
                addTagTypeByTagType(tagType);
            else
                updateTagType(tagType);
            //2.查找刚才保存的标签类目
            TagType tagt = findTagTypeByTagTypeId(targetId, tagType);
            if(tagt == null)
                return false;

            //3.保存类目下的一级标签
            for(MyParentTag mpt : tags){
                Tag pTag = new Tag();
                if(!"".equals(mpt.getParentTagName()) && null != mpt.getParentTagName()){

                    if(mpt.getParentId() == null){ //如果tagid为空说明新标签,需要保存

                        pTag.setTagName(mpt.getParentTagName());
                        pTag.setTagTypeId(tagt.getTagTypeId());
                        pTag.setProjectId(targetId);
                        pTag.setTagStatus(mpt.getParentTagStatus());
                        pTag.setOriginalTag(mpt.getOriginalTag());
                        addTag(pTag);
                    }else{
                        pTag.setTagId(mpt.getParentId());
                        pTag.setTagName(mpt.getParentTagName());
                        pTag.setTagTypeId(tagt.getTagTypeId());
                        pTag.setProjectId(targetId);
                        pTag.setTagStatus(mpt.getParentTagStatus());
                        pTag.setOriginalTag(mpt.getOriginalTag());
                        addTag(pTag);
                    }
                }


                //4.查找刚才保存的一级标签
                Tag tag = findTagByTagName(pTag.getTagName(), tagt.getTagTypeId(), targetId);

                if(tag != null){

                    List<MyChildTag> list =  mpt.getTags();


                    //5.保存二级标签
                    for(MyChildTag mct : list){
                        Tag cTag = new Tag();
                        //System.out.println(mct.get("childId"));
                        if(mct.getChildId() == null){
                            cTag.setParentTagId(tag.getTagId());
                            cTag.setProjectId(targetId);
                            cTag.setTagName(mct.getChildTagName());
                            cTag.setTagTypeId(tagt.getTagTypeId());
                            cTag.setTagStatus(mct.getChildTagStatus());
                            cTag.setOriginalTag(1);//子标签是能删除的
                            addTag(cTag);
                        }else{
                            cTag.setTagId(mct.getChildId());
                            cTag.setParentTagId(tag.getTagId());
                            cTag.setProjectId(targetId);
                            cTag.setTagName(mct.getChildTagName());
                            cTag.setTagTypeId(tagt.getTagTypeId());
                            cTag.setTagStatus(mct.getChildTagStatus());
                            cTag.setOriginalTag(1);//子标签是能删除的
                            addTag(cTag);
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }

这个功能总算是功夫不负有心人。

最后

以上就是俭朴红酒为你收集整理的多层级标签的提交,利用jquery拼接json,后台转java对象的全部内容,希望文章能够帮你解决多层级标签的提交,利用jquery拼接json,后台转java对象所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部