Stage 4 day 9.27 Spring Boot

1. Commodity background management

1.1 dynamically realize commodity classification display

1.1.1 description of asynchronous tree loading control

1). Tree control tree

`Each node has the following attributes:

id: node ID,Important for loading remote data.
text: Displays the node text.
state: Node status,'open' or 'closed',Default:'open'. If yes'closed'When, the node will not be automatically expanded.
checked: Indicates whether the node is selected.
attributes: Custom attributes added to the node.
children: An array of nodes declares several nodes.` 


2). Asynchronous tree description
The tree control reads the URL. The loading of child nodes depends on the state of the parent node. When a closed node is expanded, if the node does not load child nodes, it will take the value of node id as the http request parameter and name it 'id', and send it to the server through the URL to retrieve the child nodes.
If the user clicks the parent node and needs to expand the child node, the id value of the parent node will be passed as a parameter

1.1.2 edit itemcatcontroller (method 1)

 `/**
     * Business requirements: users can dynamically obtain the data of tree structure through ajax request
     * url:  http://localhost:8091/item/cat/list
     * Parameter: only query level 1 commodity classification information. parentId = 0
     * Return value result: List < easyuitree >
     *
     *  matters needing attention:
     *          1.No information will be passed during tree initialization Id is passed only when child nodes are expanded
     *          2.What kind of data does the page deliver and what kind of data must the backend receive
     *
     *  id: 296
     */
    @RequestMapping("/list")
    public List<EasyUITree> findItemCatList(Long id){

        Long parentId = (id==null?0L:id);
        return itemCatService.findItemCatList(parentId);
    }` 

1.1.3 edit itemcatcontroller (mode 2)

Annotation can be used to dynamically obtain parameters and realize transformation

`//2. General writing business needs to see the name and meaning
    @RequestMapping("/list")
    public List<EasyUITree> findItemCatList(
                @RequestParam(value = "id",defaultValue = "0") Long parentId){

        //Mode 1
        //Long parentId = (id==null?0L:id);
        return itemCatService.findItemCatList(parentId);
    }` 

1.2 description of spring MVC parameter transfer

`/**
     * Page parameters: http: / / request path: / method name? id=1  name="tomcat"
     * Object: 1 The request object page gives the server parameter 2 The response object is the server's response data to the page
     *
     * @param id
     * @param name
     * @return
     */
    @RequestMapping("/xxxx")
    public String xxx(Long id, String name, Item item){

        /*
        1.Basic type attribute assignment
        String id = request.getParameter("id");
        Long idLong = Long.valueOf(id);
        String strArray = request.getParameter("array");
        String[]  strArrays = strArray.split(",");
        String name = request.getParameter("namexxxxx");*/
        //2. Use the item object to get the attribute
        /*item.getId() ~~~~Remove the prefix of get ~ ~ ~ ~ ~ ~ ~ id ~ ~ initial lowercase ~ ~ ~ "id"
        String id = request.getParameter("id");
        id----Encapsulate set method -- execute business and call item setId(id);
        Item.......*/
    }` 

Summary:
1. Edit the html tag correctly. The name attribute must be written correctly. Generally, it is the same as the pojo attribute
2. When receiving parameters, verify whether the attribute type and attribute name are correct The POJO attribute must write the wrapper type
3. Some specific attributes can be dynamically transformed into array / list set / map set using spring MVC

1.3 new products

1.3.1 page analysis

1).url analysis

2). parameter analysis

3). Page JS analysis

 `/*
           * $.post(url Address, parameter, callback function)
           ajax There are several types of parameter passing:
                1.json Format {"id":"1","name":"tomcat"}
                2.String splicing "id = 1 & name ='tomcat '"
        */
        $.post("/item/save",$("#itemAddForm").serialize(), function(data){
            if(data.status == 200){
                $.messager.alert('Tips','Successfully added product!');
            }else{
                $.messager.alert("Tips","Failed to add product!");
            }
        });` 


1.3.2 creation of sysresult VO object

`package com.jt.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

//The main purpose of SysResult is to interact with the page ajax/json
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class SysResult {

    private Integer status;  //200 success 201 failure
    private String  msg;     //Server prompt message succeeded or failed
    private Object  data;    //Server data return value

    //You can use static's static method to return data dynamically
    public static SysResult fail(){

        return new SysResult(201, "Business execution failed", null);
    }

    /**
     *  1.Only the status code information 200 needs to be returned
     *  2.Need to return status and business data 200/data
     *  3.Return prompt / data business data
     * @return
     */
    public static SysResult success(){

        return new SysResult(200, "Successful business execution!", null);
    }
    //String json = "{key:value}"
    public static SysResult success(Object data){

        return new SysResult(200, "Successful business execution!", data);
    }

    //Just want to return a prompt
    public static SysResult success(String msg,Object data){

        return new SysResult(200, msg, data);
    }
}` 


1.3.3 edit ItemController

`@RequestMapping("/save")
    public SysResult saveItem(Item item){
        try {
            itemService.saveItem(item);
            return SysResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return SysResult.fail();
        }
    }` 

1.3.4 edit ItemService

`@Override
    public void saveItem(Item item) {
        //Think: if you need to manipulate public properties every time you edit the database
        Date date = new Date();
        item.setStatus(1).setCreated(date).setUpdated(date);
        itemMapper.insert(item);
    }` 


1.4 global exception handling mechanism

1.4.1 business requirements

If you add try cache to the code frequently, it will lead to poor readability and difficult maintenance of the code
For example:

1.4.2 define the handling mechanism of global exceptions

`package com.jt.aop;

import com.jt.vo.SysResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

//@ControllerAdvice / / intercept the controller layer
//@ResponseBody
@RestControllerAdvice   //Define the handling class of global exception AOP = exception notification
public class SystemAOP {

    /**
     *  Define the method of global exception. When any exception is encountered, the program starts to execute the general class type of parameters
     *  If an exception occurs, you should output the exception information and then return the error data
     */
    @ExceptionHandler({RuntimeException.class})
    public Object systemAop(Exception e){
        e.printStackTrace();
        return SysResult.fail();
    }
}` 

1.5 automatic attribute filling function

1.5.1 MP auto fill description

`//pojo base class, complete 2 tasks and 2 dates, realize serialization
@Data
@Accessors(chain=true)
public class BasePojo implements Serializable{
    @TableField(fill = FieldFill.INSERT) //Automatically add when warehousing
    private Date created;
    @TableField(fill = FieldFill.INSERT_UPDATE) //Automatic addition of warehousing / updating operations
    private Date updated;

}` 



1.5.2 automatic code filling function

Auto fill in JT common code

`package com.jt.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component  //Leave the object to the spring container for management
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date(); //Ensure consistent time
        this.setInsertFieldValByName("created", date,metaObject);
        this.setInsertFieldValByName("updated", date,metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        this.setUpdateFieldValByName("updated", new Date(), metaObject);

    }
}` 

1.6 echo update operation of commodity classification catalog

1.6.1 page js analysis

1.6.2 page effect display

task

Complete product update / deletion / on / off shelves and other operations

Tags: Spring Boot

Posted by Liam-PHP on Fri, 13 May 2022 13:08:18 +0300