Write in front
The front end of the project uses vue implementation, the template used is vue admin template, the back end uses springboot + mybaits plus and other technologies, and the database uses mysql. The purpose of this series of articles is to teach readers to build a background management project with front-end and back-end interoperability.
In this chapter, I will teach you how to build the management background and the user login service code
1. Code generator
In the development process, in order to avoid our heavy and frequent process of creating corresponding directories and classes, we can use the code generator of mybatis plus. AutoGenerator can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules, which greatly improves the development efficiency.
1.1 what is a code generator
AutoGenerator is the code generator of mybatis plus. Through AutoGenerator, you can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules, which greatly improves the development efficiency.
Special note:
What parameters are available for custom templates? Github (opens new window) All values of objectMap returned by getObjectMap method in AbstractTemplateEngine class are available.
1.2 use steps
Add corresponding dependency
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.2</version> </dependency>
Import template engine dependencies
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
Create a class for the code generator
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; // Demo example: execute the main method, input the table name of the module on the console, and press enter to automatically generate the table name in the corresponding project directory public class CodeGenerator { /** * <p> * Read console content * </p> */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("Please enter" + tip + ": "); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("Please enter the correct" + tip + "!"); } public static void main(String[] args) { // Code generator AutoGenerator mpg = new AutoGenerator(); // Global configuration GlobalConfig gc = new GlobalConfig(); //Get current file path String projectPath = System.getProperty("user.dir"); gc.setOutputDir("D:\\SocialContact\\socialUser" + "/src/main/java"); // gc.setOutputDir("D:\\test"); gc.setAuthor("bozhiqiang"); Open Explorer gc.setOpen(false); // gc.setSwagger2(true); Entity attribute Swagger2 annotation //Service interface: set the initial letter of the generated service interface name to I gc.setServiceName("%sService"); mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://121.196.111.120:3306/tensquare_user?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // Package configuration PackageConfig pc = new PackageConfig(); pc.setModuleName(null); pc.setParent("com.pjh"); //You can set the entity class package name without setting the default entity // pc.setEntity("entity"); //You can set the mapper package name without setting the default mapper // pc.setMapper("mapper"); //You can set the service package name without setting the default service // pc.setService("service"); //You can set the controller package name without setting the default controller // pc.setController("controller") mpg.setPackageInfo(pc); // Custom configuration InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // If the template engine is freemaker String templatePath = "/templates/mapper.xml.ftl"; // If the template engine is velocity // String templatePath = "/templates/mapper.xml.vm"; // Custom output configuration List<FileOutConfig> focList = new ArrayList<>(); // Custom configuration will be output first focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // Customize the output file name. If you set the Prefix suffix for Entity, note that the name of xml will change!! return projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // Configuration template TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // Policy configuration StrategyConfig strategy = new StrategyConfig(); //Table mapping entity - remove table prefix strategy.setNaming(NamingStrategy.underline_to_camel); //Field mapping entity --- remove underline strategy.setColumnNaming(NamingStrategy.underline_to_camel); //Open Lombok for entity class strategy.setEntityLombokModel(true); //The control layer interface uses Rest strategy.setRestControllerStyle(true); //Set the table name to map //String[] tableNames = {"table name 1", "table name 2", "table name 3", "table name x"}; //strategy.setInclude(tableNames); // strategy.setInclude("blog_tags","course","links","sys_settings","user_record"," user_say"); // Set the table name to map strategy.setInclude(scanner("Table name, separated by multiple English commas").split(",")); strategy.setControllerMappingHyphenStyle(true); //Remove table prefix strategy.setTablePrefix("m_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
1.3 relevant configuration
- Configure GlobalConfig
GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); globalConfig.setAuthor("jobob"); globalConfig.setOpen(false);
- Configure DataSourceConfig
DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); dataSourceConfig.setDriverName("com.mysql.jdbc.Driver"); dataSourceConfig.setUsername("root"); dataSourceConfig.setPassword("password");
2. User login function of background management page
Create a new module under the parent project just now. Here I name it socialUser
Then use the code generator to generate the corresponding initialization module as follows
v
2.1 jar coordinates to be imported
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>SocialContact</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>socialUser</artifactId> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>${mybatisplus-spring-boot-starter.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatisplus.version}</version> </dependency> <dependency> <groupId>org.example</groupId> <artifactId>socialContactcommon</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> </project>
2.2 preparation of configuration file
server: port: 9006 spring: application: name: socialContactUser #Specify service name datasource: url: jdbc:mysql://121.196.111.120:3306/tensquare_user?useUnicode=true&characterEncoding=utf8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver # Mybatis plus configuration mybatis-plus: # mapper-locations: classpath:/mapper/*Mapper.xml #For entity scanning, multiple package s are separated by commas or semicolons typeAliasesPackage: com.pjh.entity global-config: id-type: 1 #0: self increment of database ID 1: user input ID db-column-underline: false refresh-mapper: true configuration: map-underscore-to-camel-case: true cache-enabled: true #Global switch for configured cache lazyLoadingEnabled: true #Switch for delayed loading multipleResultSetsEnabled: true #Enable delayed loading, otherwise load attributes on demand log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #Print sql statements and try them out eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka / # service registry address register-with-eureka: true #Register yourself with the service registry fetch-registry: true #Pull service from service registry
2.3 realization of specific functions
You can see that we need to write three methods in total, and the path and request mode should be strictly consistent with that of the front end
package com.pjh.controller; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.pjh.entity.TbUser; import com.pjh.service.TbUserService; import com.socialContact.entity.Result; import com.socialContact.entity.StatusCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.print.DocFlavor; import javax.servlet.http.HttpServletRequest; import java.sql.Array; import java.sql.Wrapper; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * <p> * User front end controller * </p> * * @author bozhiqiang * @since 2021-05-08 */ @RestController @RequestMapping("/user") public class TbUserController { @Autowired private TbUserService tbUserService; /* * * Login function * */ @RequestMapping(value = "/login",method = RequestMethod.POST) public Result login(@RequestBody Map<String,Object> map){ System.out.println("Logging in"); /*Write conditional judgment statements*/ EntityWrapper<TbUser> wrapper = new EntityWrapper<>(); wrapper.eq("nickname",map.get("username")); wrapper.eq("password",map.get("password")); /*Query data*/ TbUser tbUser = tbUserService.selectOne(wrapper); /*If the user is queried, the login is successful*/ if (tbUser!=null){ HashMap<String, String> resultMap = new HashMap<>(); resultMap.put("token",tbUser.getId()); return new Result( true,StatusCode.OK,"Login successful",resultMap); }else{ return new Result( false,StatusCode.LOGINERROR,"Login failed"); } } /* * * Logout function * */ @RequestMapping(value = "/logout",method = RequestMethod.POST) public Result logout(){ System.out.println("Logging out"); return new Result(true,StatusCode.OK,"Log out"); } /* * * Get user message function * */ @RequestMapping(value = "/info",method = RequestMethod.GET) public Result info(@RequestHeader("X-Token") String token) { System.out.println("Token is:"+token); System.out.println("Getting data"); HashMap<String, String> resultMap = new HashMap<>(); /*Obtain data from the database. redis can be used to obtain data later*/ TbUser tbUser1 = tbUserService.selectById(token); resultMap.put("roles","admin"); resultMap.put("role","admin"); resultMap.put("name",tbUser1.getNickname()); resultMap.put("avatar",tbUser1.getAvatar()); TbUser tbUser = new TbUser(); return new Result(true,StatusCode.OK,"User information return",resultMap); } }
3. Docking with the front end
1. Put Vue config. Change the address in JS to the default address of the gateway
Just put Vue config. The address in JS can be changed to the default address of the gateway