Common. exception, Annotation, Node, Page

instructions

If you are lucky enough to see it, please read the following;

  • 1. This project is copied from the Guns of ABel533, and his project forks from the Guns of StyleFeng! Open source is a great place to learn.

  • 2, copyright belongs to the original author, I just learn to use. Follow the big guy’s idea, hope oneself also can become big guy. Gogogo…

  • 3. Currently, it is only a background module. I hope that when my skills are enhanced to a certain extent, I can integrate the [Guns] of StyleFeng into it.

  • Note inside is their own learning process, written by the rookie, not written by the big guy. It’s all about the big guy.

abnormal

1. Start by looking at the enumeration classes for all business exceptions.

/** * Enumeration of all business exceptions */
public enum BizExceptionEnum {

    /** * dictionary */
    DICT_EXISTED(400."The dictionary already exists"),
    ERROR_CREATE_DICT(500."Failed to create dictionary"),
    ERROR_WRAPPER_FIELD(500."Failed to wrap dictionary attributes"),

    /** * File upload */
    FILE_READING_ERROR(400."FILE_READING_ERROR!"),
    FILE_NOT_FOUND(400."FILE_NOT_FOUND!"),
    UPLOAD_ERROR(500."Error uploading picture"),

    /** * Permissions and data issues */
    DB_RESOURCE_NULL(400."The resource is not in the database"),
    NO_PERMITION(405."Permission exception"),
    REQUEST_INVALIDATE(400."Requested data format incorrect"),
    INVALID_KAPTCHA(400."Verification code is not correct"),
    CANT_DELETE_ADMIN(600."Cannot delete super administrator"),
    CANT_FREEZE_ADMIN(600."Cannot freeze super administrator"),
    CANT_CHANGE_ADMIN(600."Cannot change the super administrator role"),

    /** * Account problem */
    USER_ALREADY_REG(401."The user is already registered"),
    NO_THIS_USER(400."No such user exists"),
    USER_NOT_EXISTED(400."No such user exists"),
    ACCOUNT_FREEZED(401."Account has been frozen."),
    OLD_PWD_NOT_RIGHT(402."Old password is incorrect."),
    TWO_PWD_NOT_MATCH(405."Inconsistent passwords entered twice."),

    /** * error request */
    MENU_PCODE_COINCIDENCE(400."Menu number and subnumber do not match."),
    EXISTED_THE_MENU(400."Menu number duplicate, cannot be added"),
    DICT_MUST_BE_NUMBER(400."Dictionary values must be numbers."),
    REQUEST_NULL(400."Request error"),
    SESSION_TIMEOUT(400."Session timed out"),
    SERVER_ERROR(500."Server exception");

    BizExceptionEnum(int code, String message) {
        this.friendlyCode = code;
        this.friendlyMsg = message;
    }

    private int friendlyCode;
    private String friendlyMsg;
    private String urlPath;
    / / Setter and Getter, Constractor slightly
    BizExceptionEnum(int code, String message) {
        this.friendlyCode = code;
        this.friendlyMsg = message; }}Copy the code

The first thing you need to notice about encapsulating business exceptions is that they are inherited from RuntimeException, as discussed earlier

/** * Service exception encapsulation */
public class BussinessException extends RuntimeException {

    // The code of the friendly prompt
    private int friendlyCode;

    // Friendly hints
    private String friendlyMsg;

    // Abnormal service adjustment page
    private String urlPath;

    public BussinessException(BizExceptionEnum bizExceptionEnum) {
        this.friendlyCode = bizExceptionEnum.getCode();
        this.friendlyMsg = bizExceptionEnum.getMessage();
        this.urlPath = bizExceptionEnum.getUrlPath(); }}Copy the code

3, The utility class initialization exception, you need to pay attention to the serialVersionUID function:

  • 1. SerialVersionUID is a version identifier generated by Java for each serialized class to ensure that both the sender and the receiver receive compatible objects in the event of de-sequence.
  • 2. If the serialVersionUID of the class received by the receiver is not the same as the serialVersionUID of the class sent by the sender, InvalidClassException will be thrown in reverse sequence.
  • Serialized classes can explicitly declare the value of serialVersionUID.

Exceptions are defined in much the same way as they are defined in PayMap.

/** * Tool class initialization */
public class ToolBoxException extends RuntimeException {
    //serialVersionUID is a version identifier generated by Java for each serialized class that can be used to ensure that both the sender and the receiver receive compatible objects in the event of de-sequence.
    // If the serialVersionUID of the class received by the receiver is not the same as the serialVersionUID sent by the sender, an InvalidClassException will be thrown if the reverse sequence is performed. Serialized classes can explicitly declare the value of serialVersionUID,
    private static final long serialVersionUID = 8247610319171014183L;

    public ToolBoxException(Throwable e) {
        super(e.getMessage(),e);
    }

    public ToolBoxException(String message) {
        super(message);
    }

    public ToolBoxException(String message, Throwable throwable) {
        super(message,throwable);
    }
    public ToolBoxException(String messageTemplate, Object... params) {
        super(StrKit.format(messageTemplate,params)); }} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --/** * Verification code error **@AuthorGuo // This template is good *@DateThe 2018-03-04 12:04. * /
public class InvalidKaptchaException extends RuntimeException {}Copy the code

Custom annotations

4. Finally, take a look at custom annotations

Yuan comments:

The meta-annotation is responsible for the annotation of other annotations. Java5.0 defines four standard meta-annotation types that are used to provide annotations for other annotation types.

  • 1. @ Target
  • 2, @ Retention
  • 3, @ Documented
  • 4, @ Inherited

@Target

Purpose: To describe the scope of use of the annotation (i.e. where the described annotation can be used)

The values (ElementType) are:

  • CONSTRUCTOR: Used to describe the CONSTRUCTOR
  • 2.FIELD: Describes the domain
  • 3.LOCAL_VARIABLE: Used to describe local variables
  • 4.METHOD: Used to describe methods
  • 5.PACKAGE: Used to describe packages
  • 6.PARAMETER: Describes parameters
  • 7.TYPE: Used to describe classes, interfaces (including annotation types), or enum declarations

@Retention

Purpose: Indicates the level at which the annotation information needs to be saved and is used to describe the lifecycle of the annotation (i.e., to what extent the described annotation is valid)

The values are as follows:

  • 1.SOURCE: valid in the SOURCE file (i.e. retained in the SOURCE file)
  • 2.CLASS: valid in a CLASS file (i.e. CLASS reserved)
  • 3.RUNTIME: valid at RUNTIME (i.e., reserved at RUNTIME)

@Documented

Purpose: To describe that other types of annotations should be treated as public apis for annotated program members, and therefore can be documented by tools such as Javadoc.

@Inherited

An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited. If an annotation type with the @Inherited annotation is applied to a class, the annotation will be applied to a subclass of that class.

Next, we look at custom annotations

/** * Permissions annotation, used to check permissions specify access permissions */
@Inherited
@Retention(RetentionPolicy.RUNTIME)   // Valid at runtime
@Target({ElementType.METHOD})         // Method scope
public @interface Permission {
    String[] value() default{}; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --/** * Multiple data source identification */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface DataSource {
}
---------------------------------------------------------
/** * marks the method that needs to do business logging */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface BussinessLog {

    /** * Business name, for example :" modify menu "*/
    String value(a) default "";

    /** * The unique identifier of the modified entity, for example, the unique identifier of the menu entity is "ID" */
    String key(a) default "id";

    /** * dictionary (used to find the Chinese names of keys and fields) */
    String dict(a) default "SystemDict";
}



Copy the code

5. Let’s look at the Node class definition.

ZTree is an advanced jQuery ‘tree plug-in’. The performance is excellent, it is easy to configurw (with a full set of options), and has many advanced features (that usually only come with paid software).

zTree is open source and uses the MIT license.

  • Supports JSON data.
  • Supports both static and asynchronous (Ajax) data loading.
  • Supports multiple instances of zTree in one page.
  • ZTree3.0 can use lazy loading for large data, it can easily load tens of thousands of nodes in seconds even in the IE6 browser.
  • .

The most important is the official document to the very full(English is very important, important and important.)

ZTreeNode definition:

/** * Jquery ztree plugin node */
public class ZTreeNode {
    /** * Node ID */
    private Integer id;
    /** * Parent node ID */
    private Integer pId;
    /** * Node name */
    private String name;
    /** * Whether to open the node */
    private Boolean open;
    /** * is selected */
    private Boolean checked;
    // ignore Setter, Getter, Constructor, toString
}
Copy the code

MenuNode implements the Compareable interface and overrides the compareTo() method


@Override
public int compareTo(Object o) {
    MenuNode menuNode = (MenuNode) o;
    Integer num = menuNode.getNum();
    if (num == null) {
        num = 0;
    }
    return this.num.compareTo(num);
}
Copy the code
/**
 *
 * 菜单的节点
 */
public class MenuNode implements Comparable {
    /** * Node ID */
    private Integer id;
    /** * parent */
    private Integer parentId;
    /** * Node name */
    private String name;
    /** * Button level */
    private Integer levels;
    /** * Button level */
    private Integer ismenu;
    /** ** the sort of buttons */
    private Integer num;
    /** * node url */
    private String url;
    /** * Node icon */
    private String icon;
    /** * collection of child nodes */
    private List<MenuNode> children;
    /** * temporary collection */
    private List<MenuNode> linkedList = new ArrayList<MenuNode>();
}
Copy the code

Methods are presented separately to facilitate future review.

    /** * Build the entire menu tree */
    public void buildNodeTree(List<MenuNode> nodeList) {
        for (MenuNode treeNode : nodeList) {
            List<MenuNode> linkedList = treeNode.findChildNodes(nodeList, treeNode.getId());
            if (linkedList.size() > 0) { treeNode.setChildren(linkedList); }}}/** * Query the set of child nodes */
    public List<MenuNode> findChildNodes(List<MenuNode> nodeList, Integer parentId) {
        if (nodeList == null && parentId == null)
            return null;
        for (Iterator<MenuNode> iterator = nodeList.iterator(); iterator.hasNext(); ) {
            MenuNode node = (MenuNode) iterator.next();
            // Traverses all the children of a parent node based on the ID of that parent node passed in
            if(node.getParentId() ! =0&& parentId.equals(node.getParentId())) { recursionFn(nodeList, node, parentId); }}returnlinkedList; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --/** * traverses the children of a node */
    public void recursionFn(List<MenuNode> nodeList, MenuNode node, Integer pId) {
        List<MenuNode> childList = getChildList(nodeList, node);// Get the list of child nodes
        if (childList.size() > 0) {// Determine whether there are child nodes
            if (node.getParentId().equals(pId)) {
                linkedList.add(node);
            }
            Iterator<MenuNode> it = childList.iterator();
            while(it.hasNext()) { MenuNode n = (MenuNode) it.next(); recursionFn(nodeList, n, pId); }}else {
            if(node.getParentId().equals(pId)) { linkedList.add(node); }}}/** * get the list of child nodes */
    private List<MenuNode> getChildList(List<MenuNode> list, MenuNode node) {
        List<MenuNode> nodeList = new ArrayList<MenuNode>();
        Iterator<MenuNode> it = list.iterator();
        while (it.hasNext()) {
            MenuNode n = (MenuNode) it.next();
            if(n.getParentId().equals(node.getId())) { nodeList.add(n); }}returnnodeList; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --/** * Clear the button level resource **@param nodes
     * @return* /
    public static List<MenuNode> clearBtn(List<MenuNode> nodes) {
        ArrayList<MenuNode> noBtns = new ArrayList<MenuNode>();
        for (MenuNode node : nodes) {
            if(node.getIsmenu() == IsMenu.YES.getCode()){ noBtns.add(node); }}return noBtns;
    }

    /** * Clear all secondary menus **@param nodes
     * @return* /
    public static List<MenuNode> clearLevelTwo(List<MenuNode> nodes) {
        ArrayList<MenuNode> results = new ArrayList<MenuNode>();
        for (MenuNode node : nodes) {
            Integer levels = node.getLevels();
            if (levels.equals(1)) { results.add(node); }}returnresults; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --/** * Build menu list */
    public static List<MenuNode> buildTitle(List<MenuNode> nodes) {

        List<MenuNode> clearBtn = clearBtn(nodes);

        new MenuNode().buildNodeTree(clearBtn);

        List<MenuNode> menuNodes = clearLevelTwo(clearBtn);

        // Sort the menu
        Collections.sort(menuNodes);

        // Sort the submenus of the menu
        for (MenuNode menuNode : menuNodes) {
            if(menuNode.getChildren() ! =null && menuNode.getChildren().size() > 0) { Collections.sort(menuNode.getChildren()); }}// If the interface document is closed, the interface document menu is not displayed
        GunsProperties gunsProperties = SpringContextHolder.getBean(GunsProperties.class);
        if(! gunsProperties.getSwaggerOpen()) { List<MenuNode> menuNodesCopy =new ArrayList<>();
            for (MenuNode menuNode : menuNodes) {
                if (Const.API_MENU_NAME.equals(menuNode.getName())) {
                    continue;
                } else {
                    menuNodesCopy.add(menuNode);
                }
            }
            menuNodes = menuNodesCopy;
        }

        return menuNodes;
    }
Copy the code

ZTree is easy to use

Gets all selection nodes and gets child nodes

// Get the tree by id number
var treeObj2 = $.fn.zTree.getZTreeObj("treeDemo");
// Get all selected nodes to get a list of nodes
var nodes2 = treeObj2.getCheckedNodes(true);
// If it is a leaf node, take out the id
var idlist = [];
$.each(nodes2, function (i, item) {
    if(! item.isParent) {//alert(item.id + "," + item.name);idlist.push(item.id); }}); console.log(idlist);Copy the code

6, next, let’s look at PageHelper,Mybatis general pagination plugin this plugin is also written by the project leader. You can encapsulate it yourself if you have to, but you won’t encapsulate it yourself if you’ve used it. Mainly the PageInfo class.

package com.guo.guns.common.page;

import com.github.pagehelper.Page;

import java.util.List;

/** * Encapsulate the paging result (for Bootstrap Table) **@Author guo
 * @DateThe 2018-03-04 shouldest be * /
public class PageInfoBT<T> {

    /** * result set */
    private List<T> rows;

    /** ** total */
    private long total;

    public PageInfoBT(List<T> page) {
        this.rows = page;
        if (page instanceof Page) {
            this.total = ((Page) page).getTotal();
        } else {
            this.total = page.size(); }}/ / Setter and Getter slightly
}

Copy the code

PageHelper is simple to use

1. Check the data on the first page, 5 items per page:

 PageHelper.offsetPage(0.5);
Copy the code

(2) Total amount obtained:

PageInfo pageInfo = new PageInfo<>(cs);
System.out.println("Total:"+pageInfo.getTotal());
System.out.println(pageInfo);
Copy the code