Building Blog Websites from Zero Based on SpringBook - Adding Column Creation, Modification and Deletation Functions

Watch Blog is a function that supports the creation of columns, that is, a series of related articles can be archived into columns, to facilitate user management and access to articles. Here we mainly explain the creation, modification and deletion of columns. As for the columns, there are other functions involved, such as attention columns, which will be introduced in the follow-up.

1. Creating Columns

The method of receiving and processing column-related functions is placed in the GroupController class. First, the page of the column is created as follows:

Here are two points that need special explanation:

First, this classification data is the classification data of this blog website. This classification data is added when the system is initialized. This initialization function will be added later. At present, here is to write the data into the database in advance. For example, this blog as a technical blog, the classification is: front-end. Architecture, Block Chain, Cloud Computing, etc.

Then the categorized information data will not be modified after initialization. Then the data will be put into the cache, that is, Category Cache:

/**
 * Cache classification information
 * The classification information is stored in the permanent cache of the system in the form of "_CATEGORY"+categoryId as the key and value as the classification information object.
 *
 * @author lzj
 * @since 1.0
 * @date [2019-07-22]
 */
@Slf4j
@DependsOn("categoryService")
@Component("categoryCache")
public class CategoryCache implements ICache<List<Category>> {

    /**
     * Injecting an instance of Cache interface based on Spring, implemented by default by Ehcache
     * TODO It can also be implemented by Redis and Memcached in the future.
     */
    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private ICategoryService categoryService;

    /**
     * Cache instances
     */
    private Cache cache;

    /**
     * key Prefix
     */
    private String keyPrefix = "_CATEGORY";

    /**
     * Classification information root node ID
     */
    public static final String ROOT_CATEGORY_ID = "0";

    @PostConstruct
    public void init() {
        // Get a system permanent cache instance
        cache = cacheManager.getCache(Const.CACHE_SYSTEM_ETERNAL);
        log.info("Get a system permanent cache instance");

        log.debug("Start loading parent classification information");
        List<Category> categorys = categoryService.getByParentId(ROOT_CATEGORY_ID);
        if (categorys != null && !categorys.isEmpty()) {
            put(keyPrefix + ROOT_CATEGORY_ID, categorys);
        }
        log.debug("Loading parent classification information");
    }

    @Override
    public List<Category> get(Object key) {
        Cache.ValueWrapper valueWrapper = cache.get(keyPrefix + key);
        if (valueWrapper == null) {
            // Reload once from the database
            List<Category> categorys = categoryService.getByParentId((String) key);
            if (categorys == null) {
                return null;
            }

            // Put it in the cache again
            put(key, categorys);

            return categorys;
        }
        return (List<Category>) valueWrapper.get();
    }

    @Override
    public void put(Object key, List<Category> value) {
        cache.put(keyPrefix + key, value);
    }

    @Override
    public void remove(Object key) {
        cache.evict(keyPrefix + key);
    }
}

Secondly, the upload control here is webuploader. If the upload file is processed by webuploader, it needs to be initialized as follows:

$(function() {
    var _list = $('#fileList');
    var ratio = window.devicePixelRatio || 1;
    var thumbnailWidth = 100 * ratio;
    var thumbnailHeight = 100 * ratio;

    // Initialize Web Uploader
    var uploader = WebUploader.create({

        // Whether to upload files automatically after selecting them.
        auto: true,

        // swf file path
        swf: '${rc.contextPath}/static/plugins/webuploader/Uploader.swf',

        // File receiving server.
        server: '${rc.contextPath}/upload',

        // Select the button for the file. Optional.
        // Internally, based on the current operation, it may be an input element or flash.
        pick: '#filePicker',

        fileVal: "_uploadFile",

        formData: {
            _distId:'_distId',
            _distType:'_groupLogo',
        },

        // Only picture files are allowed to be selected.
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,png',
            mimeTypes: 'image/*'
        },

        fileNumLimit: 1,
        fileSizeLimit: 2 * 1024 * 1024,    // 2 M
        fileSingleSizeLimit: 2 * 1024 * 1024    // 2 M
    });

    // When files are added
    uploader.on( 'fileQueued', function( file ) {
        var li = $(
            '<div id="' + file.id + '" class="file-item thumbnail text-center">' +
            '<img>' +
            // '<div class="info">' + file.name + '</div>' +
            '</div>'
            ),
            img = li.find('img');


        // _ list is a container jQuery instance
        _list.append( li );

        // Create Thumbnail
        // If it's a non-picture file, you don't need to call this method.
        // Thumbnail Width x thumbnail Height is 100 x 100
        uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
                img.replaceWith('<span>Unable to preview</span>');
                return;
            }

            img.attr( 'src', src );
        }, thumbnailWidth, thumbnailHeight );
    });

    // Create progress bar to display in real time during file upload.
    uploader.on( 'uploadProgress', function( file, percentage ) {
    });

    // File upload is successful, add successful class to item, and upload successfully with style tags.
    uploader.on( 'uploadSuccess', function(file, response) {
        $( '#'+file.id ).addClass('upload-state-done');
        $( '#'+file.id). append ('<a class= "del" href= "javascript: void (0);">delete </a>')
        $("#logo").val(response.url);
    });

    // File upload failed, showing upload error.
    uploader.on( 'uploadError', function( file ) {
        var li = $( '#'+file.id ),
            error = li.find('div.error');

        // Avoid duplicate creation
        if ( !error.length ) {
            error = $('<div class="error"></div>').appendTo( li );
        }

        error.text('Upload failure');
    });

    // Finish uploading, success or failure, delete progress bar first.
    uploader.on( 'uploadComplete', function( file ) {
    });

    // Execute deletion method
    _list.on('click', '.del', function () {
        var Id = $(this).parent().attr('id');
        //Delete the picture
        uploader.removeFile(uploader.getFile(Id, true));
        $(this).parent().remove();
        $("#logo").val("");
    });
});

Here, the background needs to process the information of the Logo image in the column. According to the way in the previous chapter, there are UploadGroupLogoHandler classes, such as:

/**
 * Upload Column Logo Processing Class
 *
 * @author lzj
 * @since 1.0
 * @date [2019-07-23]
 */
@Slf4j
@Component("_groupLogo")
public class UploadGroupLogoHandler implements IUploadHandler {

    @Resource(name = "configCache")
    private ICache<Config> configCache;

    @Override
    public Object upload(MultipartFile file, String distType, String userId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            // Get the original name of the picture
            String originalName = file.getOriginalFilename();

            // Judging the Type of Picture
            if (!(originalName.endsWith(".jpg") || originalName.endsWith(".JPG") || originalName.endsWith(".png") || originalName.endsWith(".PNG") || originalName.endsWith(".gif") || originalName.endsWith(".GIF") || originalName.endsWith(".jpeg") || originalName.endsWith(".JPEG"))) {
                throw new TipException("The type of picture you uploaded is incorrect. Please upload the format as follows jpg,png or gif");
            }

            // Get the size of the picture
            long fileSize = file.getSize();

            // Picture size should not exceed 2M, 2M = 2 * 1024 * 1024B = 2097152B
            if (fileSize > 2097152L) {
                throw new TipException("You uploaded more than 2 pictures M");
            }

            Config config = configCache.get(Config.CONFIG_IMG_GROUP_LOGO_PATH);
            // The root directory for saving the head image
            String basePath = config.getConfigValue();
            if (!(basePath.endsWith("/") || basePath.endsWith("\\"))) {
                basePath += "/";
            }

            // Build yyyyMM folders according to the current time, and create month-to-month folders
            String dateDirName = DateUtil.date2Str(new Date(), DateUtil.YEAR_MONTH_FORMAT);
            basePath += dateDirName;

            File imageDir = new File(basePath);
            if (!imageDir.exists()) {
                imageDir.mkdirs();
            }

            String fileNewName = IdGenarator.guid() + originalName.substring(originalName.lastIndexOf("."));
            FileUtil.copy(file.getInputStream(), new FileOutputStream(new File(imageDir, fileNewName)));

            result.put("url", dateDirName + "/" + fileNewName);
            result.put("msg", "Upload Success");
        } catch (TipException e) {
            result.put("url", "");
            result.put("msg", e.getMessage());
        } catch (Exception e) {
            log.error("Upload failure", e);
            result.put("url", "");
            result.put("msg", "Upload failure");
        }
        return result;
    }

    @Override
    public void download(String fileId, HttpServletResponse response) throws Exception {
    }

    @Override
    public Object list(String distType, String userId) throws Exception {
        return null;
    }
}

Finally, the core code for creating the column is as follows:

/**
 * Create columns
 *
 * @param request
 * @param session
 * @return
 */
@RequestMapping(value = "/user/group/add", method = RequestMethod.POST)
@ResponseBody
public Result add(HttpServletRequest request, HttpSession session) {
    Result result = new Result();
    try {
        // Receiving parameters
        String categoryId = request.getParameter("categoryId");
        String name = request.getParameter("name");
        String logo = request.getParameter("logo");
        String introduce = request.getParameter("introduce");

        // Calibration parameters
        if (StringUtils.isEmpty(categoryId) || StringUtils.isEmpty(name) || StringUtils.isEmpty(logo) || StringUtils.isEmpty(introduce)) {
            throw new TipException("Lack of necessary parameters");
        }

        // Get login information
        User tempUser = (User) session.getAttribute(Const.SESSION_USER);
        String userId = tempUser.getUserId();

        // Building Column Objects
        Group group = new Group();
        group.setGroupId(IdGenarator.longIdStr());
        group.setName(name);
        group.setLogo(logo);
        group.setIntroduce(introduce);
        group.setCategoryId(categoryId);
        group.setCreator(userId);
        group.setCreateTime(new Date());
        // Whether to Audit Columns Obtained from System Configuration Items
        Config config = configCache.get(Config.CONFIG_GROUP_AUDIT);
        if (config != null && "1".equals(config.getConfigValue())) {
            // Need to be audited
            group.setStatus(Group.STATUS_NO);
        } else {
            // No audit is required
            group.setStatus(Group.STATUS_SUCCESS);
        }

        // Save column information
        boolean flag = groupService.save(group);
        if (!flag) {
            throw new TipException("Failure to create columns");
        }

        result.setCode(Result.CODE_SUCCESS);
        result.setMsg("Successful Column Creation");
    } catch (TipException e) {
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg(e.getMessage());
    } catch (Exception e) {
        log.error("Failure to create columns", e);
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg("Failure to create columns");
    }
    return result;
}

2. Revision column

With the foundation of the previous new column, in fact, the function of modifying the column is relatively simple. Here only lists the core code to deal with the modification, such as:

/**
 * Revision column
 *
 * @param groupId
 * @param request
 * @param session
 * @return
 */
@RequestMapping(value = "/user/group/edit/{groupId}", method = RequestMethod.POST)
@ResponseBody
public Result edit(@PathVariable("groupId") String groupId, HttpServletRequest request, HttpSession session) {
    Result result = new Result();
    try {
        // Get column information based on id
        Group group = groupService.getById(groupId);
        if (group == null || StringUtils.isEmpty(group.getGroupId())) {
            log.error("groupId: " + groupId + ": This column does not exist");
            throw new TipException("This column does not exist");
        }

        // Getting User Information
        User tempUser = (User) session.getAttribute(Const.SESSION_USER);
        String userId = tempUser.getUserId();
        if (!userId.equals(group.getCreator())) {
            log.error("userId: " + userId + "Modify someone else's groupId: " + groupId);
            throw new TipException("Can't modify other people's columns");
        }

        // Receiving parameters
        String categoryId = request.getParameter("categoryId");
        String name = request.getParameter("name");
        String introduce = request.getParameter("introduce");
        String logo = request.getParameter("logo");

        // Calibration parameters
        if (StringUtils.isEmpty(categoryId) || StringUtils.isEmpty(name) || StringUtils.isEmpty(introduce)) {
            throw new TipException("Lack of necessary parameters");
        }

        group.setCategoryId(categoryId);
        group.setName(name);
        group.setIntroduce(introduce);
        if (!StringUtils.isEmpty(logo)) {
            group.setLogo(logo);
        }
        group.setUpdateTime(new Date());

        // modify
        boolean flag = groupService.updateById(group);
        if (!flag) {
            throw new TipException("Failure to modify column");
        }

        result.setCode(Result.CODE_SUCCESS);
        result.setMsg("Successful revision of the column");
    } catch (TipException e) {
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg(e.getMessage());
    } catch (Exception e) {
        log.error("Failure to modify column", e);
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg("Failure to modify column");

    }
    return result;
}

3. Delete columns

The function of deleting columns is very simple, but we need to consider that after deleting columns, we need to deal with other data information associated with them. Because other modules have not been completed, we will add a TODO first, and then deal with it later. The core code for deleting the column is as follows:

/**
 * Delete columns based on ID
 *
 * @param groupId
 * @param session
 * @return
 */
@RequestMapping(value = "/user/group/delete/{groupId}", method = RequestMethod.GET)
@ResponseBody
public Result delete(@PathVariable("groupId") String groupId, HttpSession session) {
    Result result = new Result();
    try {
        // Get column information based on id
        Group group = groupService.getById(groupId);
        if (group == null || StringUtils.isEmpty(group.getGroupId())) {
            log.error("groupId: " + groupId + ": This column does not exist");
            throw new TipException("This column does not exist");
        }

        // Getting User Information
        User tempUser = (User) session.getAttribute(Const.SESSION_USER);
        String userId = tempUser.getUserId();
        if (!userId.equals(group.getCreator())) {
            log.error("userId: " + userId + "Delete someone else's groupId: " + groupId);
            throw new TipException("Can't delete other people's columns");
        }

        // delete
        boolean flag = groupService.removeById(groupId);
        if (!flag) {
            throw new TipException("Failed to delete columns");
        }

        // After TODO deletes the column, it needs to process other related data, because other modules have not yet been processed here.

        result.setCode(Result.CODE_SUCCESS);
        result.setMsg("Successful deletion of columns");
    } catch (TipException e) {
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg(e.getMessage());
    } catch (Exception e) {
        log.error("Failed to delete columns", e);
        result.setCode(Result.CODE_EXCEPTION);
        result.setMsg("Failed to delete columns");
    }
    return result;
}

Pay attention to me

Pay attention to me in your most convenient way:
Wechat Public Number:

Keywords: PHP Session Database Spring Ehcache

Added by BillyBoB on Tue, 30 Jul 2019 08:43:50 +0300