SpringBoot+MyBatisPlus+Vue 앞 뒤 분리 프로젝트 빠 른 구축 과정(백 엔 드)

데이터베이스 준비
data_test.sql:

/*
SQLyog Enterprise v12.08 (64 bit)
MySQL - 5.7.31 : Database - data_test
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`data_test` /*!40100 DEFAULT CHARACTER SET utf8  */;

USE `data_test`;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) CHARACTER SET utf8  NOT NULL COMMENT '  ',
  `password` varchar(50) CHARACTER SET utf8  NOT NULL COMMENT '  ',
  `user_state` varchar(10) CHARACTER SET utf8  NOT NULL DEFAULT '1' COMMENT '  ,    ',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

LOCK TABLES `user` WRITE;

insert  into `user`(`user_id`,`user_name`,`password`,`user_state`) values (1,'keafmd','keafmd','1'),(3,'21312321','123','0'),(11,'213','213','1'),(12,'keafmd','666','0');

UNLOCK TABLES;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
백 엔 드 구축
1.SpringBoot 프로젝트 를 빠르게 만 듭 니 다.
STEP 1:Spring Initializr
在这里插入图片描述
두 번 째 단계:Spring Initializr 프로젝트 설정
在这里插入图片描述
STEP 3:Lombok 도구 추가
在这里插入图片描述
STEP 4:Finish
在这里插入图片描述
초기 화 된 모습:
在这里插入图片描述
2.의존 도입
여기에 전체 pom.xml 를 붙 이 고 일부 의존 은 간단 한 수요 에 있어 불필요 할 수 있 으 며 스스로 버 릴 수 있 습 니 다.
pom.xml 코드:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.keafmd</groupId>
    <artifactId>springboot-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-server</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>


        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>io.github.yedaxia</groupId>
            <artifactId>japidocs</artifactId>
            <version>1.4.3</version>
            <scope>test</scope>

        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>


        <!--      https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.68</version>
        </dependency>

        <!--JWT    -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
3.코드 를 작성 하여 코드 를 신속하게 생 성 합 니 다.
이 코드 는 보조 코드 이기 때문에 test 패키지 에 넣 으 면 됩 니 다.관련 데이터 베이스 정보 와 패키지 정 보 는 당신들 의 것 과 일치 해 야 합 니 다.스스로 수정 해 야 합 니 다.가방 의 이름 이 저 와 일치 하 는 지 는 데이터 베이스 관련 정 보 를 수정 하면 됩 니 다.
CodeGenerator:

package com.keafmd.mp;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Keafmd
 *
 * @ClassName: CodeGenerator
 * @Description:      
 * @author:       
 * @Date: 2021-04-29 17:06
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class CodeGenerator {

    /**
     * <p>
     *        
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("   " + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("      " + tip + "!");
    }

    public static void main(String[] args) {
        //      
        AutoGenerator mpg = new AutoGenerator();

        //     
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
//        System.out.println("projectPath = " + projectPath);
        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setOutputDir("D:\\test");
        gc.setAuthor("     :      ");
        gc.setOpen(false);
        // gc.setSwagger2(true);      Swagger2   
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);

        //      
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/data_test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("18044229");
        mpg.setDataSource(dsc);

        //    
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.keafmd");
        mpg.setPackageInfo(pc);

        //      
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        //         freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        //         velocity
        // String templatePath = "/templates/mapper.xml.vm";

        //        
        List<FileOutConfig> focList = new ArrayList<>();
        //            
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //          ,     Entity       、     xml           !!
                return projectPath + "/src/main/resources/com/keafmd/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //     
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        //     
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("  ,        ").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("m_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
4.실행 코드 생 성기 생 성 코드
콘 솔 에 user(표 이름)를 입력 하 십시오.
在这里插入图片描述
빨간색 상자 안에 자동 으로 생 성 되 는 코드:
在这里插入图片描述
5、application.properties 작성
개인 습관 은 application.properties 를 application.yml 로 바 꾸 고 포트 를 80 으로 바 꿉 니 다.

server:
  port: 80

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1/data_test?useSSL=false&&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 18044229

  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false
6.시작 클래스 에@MapperScan 추가
SpringbootServerApplication:

package com.keafmd;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.keafmd.mapper")
public class SpringbootServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootServerApplication.class, args);
    }

}
7.테스트 코드 를 작성 하여 데이터베이스 연결 이 올 바른 지 테스트 합 니 다.
1.UserMapper 코드 페이지 의 대괄호 안에 Alt+Insert 를 누 르 고 Test 를 선택 합 니 다.
在这里插入图片描述
2、Ok
在这里插入图片描述
3.테스트 클래스 자동 생 성
在这里插入图片描述
4.테스트 코드 작성
UserMapperTest :

package com.keafmd.mapper;

import com.keafmd.SpringbootServerApplication;
import com.keafmd.entity.User;
import com.keafmd.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest(classes = SpringbootServerApplication.class)
class UserMapperTest {

    @Resource
    UserService userService;

    @Test
    public void test1(){
        List<User> userList = userService.list();
        for (User user : userList) {
            System.out.println(user);
        }

    }



}
5.테스트 결과
在这里插入图片描述
이로써 백 엔 드 와 데이터베이스 연결 은 문제 가 없다.
8.백 엔 드 의 도구 류 코드 를 작성 합 니 다(패키지 결과 집합,날짜 처리,크로스 도 메 인 요청 해결)
在这里插入图片描述
1、CommonResult

package com.keafmd.common;

import lombok.Getter;

/**
 * Keafmd
 *
 * @ClassName: CommonResult
 * @Description:      
 * @author:       
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Getter
public class CommonResult  {
    private Integer code;
    private String message;
    private Object obj;

    private CommonResult(Integer code, String message, Object obj) {
        this.code = code;
        this.message = message;
        this.obj = obj;
    }

    public static CommonResult nohandler() {
        return new CommonResult(ResultCode.NOHANDLER.getCode(), ResultCode.NOHANDLER.getMessage(),null);
    }
    public static CommonResult success(Object data) {
        return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),data);
    }
    public static CommonResult failed() {
        return new CommonResult(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage(),null);
    }
    public static CommonResult failed(String message) {
        return new CommonResult(ResultCode.FAILED.getCode(),message,null);
    }
    public static CommonResult notoken() {
        return new CommonResult(ResultCode.NOTOKEN.getCode(), ResultCode.NOTOKEN.getMessage(),null);
    }
    public static CommonResult nopremiss() {
        return new CommonResult(ResultCode.NOPERMISS.getCode(), ResultCode.NOPERMISS.getMessage(),null);
    }
}
2、DateConverter

package com.keafmd.common;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Keafmd
 *
 * @ClassName: DateConverter
 * @Description:     
 * @author:       
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Configuration
public class DateConverter implements Converter<String, Date> {

    public DateConverter() {
//        System.out.println("   ........");
    }

    static List<SimpleDateFormat> sdfs = new ArrayList();

    static {
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd"));

    }

    @Override
    public Date convert(String s) {
        SimpleDateFormat sdf = null;
        if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", s)) {
            sdf = sdfs.get(1);
        }
        else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}$", s)){
            sdf = sdfs.get(0);
        }
        else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", s)){
            sdf = sdfs.get(3);
        }
        else if (Pattern.matches("^\\d{4}-\\d{2}/-\\d{2}}$", s)){
            sdf = sdfs.get(2);
        }

        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;

    }
}
3、LocalDateTimeConverter

package com.keafmd.common;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Keafmd
 *
 * @ClassName: LocalDateTimeConverter
 * @Description:     
 * @author:       
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    //2021-04-29%2001:02:03
    @Override
    public LocalDateTime convert(String s) {
        return LocalDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}
4、ResultCode

package com.keafmd.common;

import lombok.Getter;

/**
 * Keafmd
 *
 * @ClassName: ResultCode
 * @Description:     
 * @author:       
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Getter
public enum ResultCode {
    NOHANDLER(404,"      "),
    SUCCESS(200,"    "),
    FAILED(500,"    "),
    NOTOKEN(401,"         "),
    NOPERMISS(403,"     "),
    ;

    private Integer code;
    private String message;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }



}
5、AppConfig

package com.keafmd.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.keafmd.common.DateConverter;
import com.keafmd.common.LocalDateTimeConverter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: AppConfig
 * @Description:       
 * @author:       
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Configuration
public class AppConfig extends WebMvcConfigurationSupport {

    /**
     *     
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDialect(new MySqlDialect());
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
    @Bean
    FilterRegistrationBean<CorsFilter> cors(){
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<CorsFilter>();
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://127.0.0.1:81");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        CorsFilter filter = new CorsFilter(source);
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }


    /**
     * curl http://127.0.0.1/user/getById?id=31
     * @param converters
     */

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//        objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //   null   

        JavaTimeModule javaTimeModule = new JavaTimeModule();

        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

//        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        objectMapper.registerModule(javaTimeModule);
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
    }

    @Override
    protected void addFormatters(FormatterRegistry registry) {
        super.addFormatters(registry);
        registry.addConverter(new DateConverter());
        registry.addConverter(new LocalDateTimeConverter());
    }
}
6、DefaultExceptionHandler

package com.keafmd.config;

import com.keafmd.common.CommonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * Keafmd
 *
 * @ClassName: DefaultExceptionHandler
 * @Description:
 * @author:       
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@RestControllerAdvice
public class DefaultExceptionHandler {

    @ExceptionHandler
    public CommonResult exceptionHandler(HttpServletRequest request, Exception ex) {
        ex.printStackTrace();
        if(ex instanceof NoHandlerFoundException) {
            return CommonResult.nohandler();
        }
        return CommonResult.failed(ex.getMessage());
    }


}
9.백 엔 드 의 첨삭 검사 코드 작성
1.UserService 인터페이스 에서 페이지 조회 코드 작성

package com.keafmd.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keafmd.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *     
 * </p>
 *
 * @author      :      
 * @since 2021-04-29
 */
public interface UserService extends IService<User> {
    Page pageList(Page page, User user);
}
2.User ServiceImpl 구현 클래스 에서 페이지 조회 와 모호 한 검색 을 실현 합 니 다.

package com.keafmd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keafmd.entity.User;
import com.keafmd.mapper.UserMapper;
import com.keafmd.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *       
 * </p>
 *
 * @author      :      
 * @since 2021-04-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Page pageList(Page page, User user) {
        if(page == null){
            page = new Page();
        }

        QueryWrapper wrapper = new QueryWrapper();
        if(user!=null && StringUtils.isNotEmpty(user.getUserName())){
            //  user_name      
            wrapper.like("user_name",user.getUserName());
        }

        return super.page(page,wrapper);
    }
}
3.UserController 에서 추가 삭제 검사 코드 를 작성 합 니 다.

package com.keafmd.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keafmd.common.CommonResult;
import com.keafmd.entity.User;
import com.keafmd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

/**
 * <p>
 *       
 * </p>
 *
 * @author      :      
 * @since 2021-04-29
 */
@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    UserService userService;

    /**
     *   
     * @return
     */
    @RequestMapping("/list")
    CommonResult list(ModelMap modelMap, Page page, @ModelAttribute("user") User user) {

        page = userService.pageList(page, user);
        modelMap.addAttribute("page", page);
        return CommonResult.success(page);
    }

    @RequestMapping("/save")
    CommonResult save(User user){

        return CommonResult.success(userService.saveOrUpdate(user));

    }


    /**
     *   id 
     * @param id
     * @return
     */
    @RequestMapping("/getById")
    CommonResult getById(Integer id) {
        return CommonResult.success(userService.getById(id));
    }

    /**
     *   ,    
     * @param id
     * @return
     */
    @RequestMapping("/del")
    CommonResult del(Integer id ) {
        User user = userService.getById(id);
        user.setUserState("0");
        return CommonResult.success(userService.updateById(user));
    }


    /**
     *     
     * @param id
     * @return
     */
    @RequestMapping("/delByIds")
    CommonResult delByIds(Integer[] id) {
        /*for (Integer integer : id) {
            System.out.println(integer);
        }*/
        return CommonResult.success(userService.removeByIds(Arrays.asList(id)));
    }

}
전면 구축
편폭 이 제한 되 어 있 기 때문에,전단 을 단독으로 한 편 더 쓰다.
SpringBoot+MyBatisPlus+Vue 전후 단 분리 프로젝트 빠 른 구축[전단 편][빠 른 백 엔 드 코드 생 성,패 키 징 결과 집합,추가 삭제 검사,모호 찾기][기본 프레임 워 크 완료]
이상 은 SpringBoot+MyBatisPlus+Vue 앞 뒤 분리 프로젝트 의 빠 른 구축[백 엔 드 편][백 엔 드 코드 빠 른 생 성,패 키 징 결과 집합,추가 삭제 검사,모호 찾기][기본 프레임 워 크 완료]의 모든 내용 입 니 다.
SpringBoot+MyBatisPlus+Vue 앞 뒤 분리 프로젝트 의 빠 른 구축 과정(백 엔 드)에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.SpringBoot+MyBatisPlus+Vue 앞 뒤 분리 구축 내용 에 대해 서 는 이전 글 을 검색 하거나 아래 의 관련 문장 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기