navigation

[react] Hooks

[Encapsulation 01- Design Pattern] Design principles and factory pattern (simple abstract approach) Adapter pattern Decorator pattern [Encapsulation 02- Design Pattern] Command pattern Enjoy pattern Composite pattern Agent pattern

[React from zero practice 01- background] code split [React from zero practice 02- background] permission control [React from zero practice 03- background] custom hooks [React from zero practice 04- background] docker-compose Deploy React + Egg +nginx+mysql [React From zero practice 05- background] Gitlab-CI using Docker automated deployment

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data reactive and initialize render [source -vue02] Computed responsive – Initialize, access, Update Procedure [source -vue04] Watch Listening properties – Initialize and update [source -vue04] vue. set and vm.$set [source -vue05] vue.extend

[source -vue06] Vue. NextTick and VM.$nextTick [Deployment 01] Nginx [Deployment 02] Docker deployVUE project [Deployment 03] Gitlab-CI

[Data Structures and Algorithms 01] Binary search and sort

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise Data Structures and Algorithms – Binary Search and Sorting Js Design Patterns – Agents, policies, singletons

/ front-end learn java01 – SpringBoot combat environment configuration and the HelloWorld service [front-end learn java02 – SpringBoot combat] mybatis + mysql implementation song to add and delete [front-end learn java03 – SpringBoot combat] Lombok, log, Java04 -SpringBoot combat deployment [front-end science Java04 -SpringBoot combat] static resources + interceptor + front and back end file upload [front-end science Java05 -SpringBoot combat] common annotates + Redis implementation statistics function [front-end science Java06 -SpringBoot combat] inject + Swagger2 3.0 + unit test JUnit5 [Front-End science Java07 -SpringBoot real World] IOC scanner + transaction + Jackson [front-end science Java08 -SpringBoot real world summary 1-7

(1) Pre-knowledge

(1) Some words

// Navicat Permium supports a variety of databases, including rainbow BRACKET brackets Wired connection auto wired automatic connection / / the @autowired conditional conditions / / @ conditional override autotype distinct preference preference clearly different The exception exceptionCopy the code

(2) MAC version idea shortcut key

  • Idea MAC shortcut keys
Command + shift + r 2. Bring up Actions Command + 3 3. Set command + 4. Jump between files Command + e 5. Message prompt Command + 1 6. Control + left mouse button 7. Copy file reference path right mouse button -copy path-copy Reference 8. Shift + TAB - Move TAB 9. Find the file - CTRL + hCopy the code

(3) Some common server application port numbers

mysql ----------------------- 3306
nginx ----------------------- 80
Copy the code

(4) The port is occupied

Lsof -i TCP :7890 kill PID // 7890 indicates the number of the occupied portCopy the code

(2) Commonly used annotations

(1) Lombok’s common annotations

(1.1) Addition and use of Lombok

  • inbean dto modelEtc
<! -- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> < artifactId > lombok < / artifactId > < version > 1.18.20 < / version > < scope > provided < / scope > < / dependency >Copy the code

@ Data (1.2)

  • @data contains the following annotations
    • @Getter/@Setter
    • @ToString
    • @EqualsAndHashCode
    • @requiredargsConstructor A constructor for specific parameters, which are variables with the final modifier added

@ Value (1.3)

  • Only the getter, and everything else, like @data, makes all variables final
  • @Getter
  • @ToString
  • @EqualsAndHashCode
  • @requiredargsConstructor A constructor for specific parameters, which are variables with the final modifier added

@ Builder (1.4)

  • @Builder automatically generates (streaming set value) writing without having to write a bunch of setters
  • @Builder a very useful note
  • Note: Usually @data and @Builder are used together because you still have to write getters/setters
@Data
@Builder
public class FirstBean {
    private String name;
    private Integer age;
    private String sex;
}

-----------------------

FirstBean firstBean = FirstBean.builder()
                .name(name)
                .age(age)
                .sex(sex)
                .build();
Copy the code

@ Slf4j (1.5)

  • @slf4j automatically generates the log static constants for this class, so sout is not required
Log.info (" passed parameter variable {}", name); // {} is a placeholder for the variable name that followsCopy the code

@ NoArgsConstructor @ AllArgsConstructor @ RequiredArgsConstructor (1.6)

  • @noargsconstructor Takes no arguments
  • @allargsconstructor Full parameter constructor
  • @requiredargsConstructor Specifies the parameter constructor

(2) Mybatis commonly used annotations

(3) Common annotations in controller

(3.1) @RestController and @Controller + @responseBody

  • @RestController
    • @RestController = @Controller + @ResponseBody
    • @RestController cannot return an HTML page. The content returned is the content of the return
    • If you have a controller, something that’s going to return HTML, something that’s going to return return, you need to annotate with @controller that the controller returns HTML, Then add @responseBody to the return method to return whatever comes after the return
  • @responseBody applies to class methods, and @RestController and @Controller apply to classes
// @RestController = @Controller + @ResponseBody @Controller --------------------------------- 1 @Slf4j public class FirstController { @RequestMapping(value = "/music/{name}", method = {RequestMethod.GET}) @ResponseBody --------------------------- 2 public String getMusic( @PathVariable("name") String name, @RequestParam("age") Integer age, @RequestParam("sex") String sex ) { System.out.println(name); Log.info (" passed parameter variable 2{}", name); FirstBean firstBean = FirstBean.builder() .name(name) .age(age) .sex(sex) .build(); System.out.println(firstBean); return "good246"; }}Copy the code

(3.2) @GetMapping @PostMapping @PutMapping @DeleteMapping

  • @GetMapping
@requestMapping (value="/music/{name}", method = {requestMethod.get})Copy the code
  • CRUD stands for CREATE Read Update DELETE

(3.3) @requestparam and @pathvariable —— get delete requests

  • There is a url address like this:www.baidu.com/music/ Jay Chou? Age =20&sex=man
  • @PathVariable
    • You can get the dynamic parameter portion of path
    • "/music/{name}"
    • @PathVariable("name") String name
  • @RequestParam
    • You can obtain the age and sex
    • @RequestParam("age") Integer age

(3.4) @RequestBody and @requestheader —— Post put requests

    @PostMapping("/music")
    public MusicBean addMusic(
            @RequestBody MusicBean musicBean,
            @RequestHeader("Content-Type") String contentType
    ) {
        log.info("musicBean:{}", musicBean);
        log.info("Content-Type:{}", contentType);
        return musicBean;
    }
Copy the code

(3-5) @RequestPart

  • @requestPart is used for submitting requests to multipart/form-data forms
  • The request mode is MultipartFile, which belongs to the Spring MultipartResolver class and is transmitted over HTTP
  • Note: The name of the front-end upload component is "aaa", which corresponds to @requestPart ("aaa") in Java
  • Combine the example uploaded below

(4) Container-related comments

(4.1) @Configuration + @Bean Adds components to the container

  • @ Configuration Configuration class
    • Tell SpringBoot this is a (configuration class)
    • @Configuration annotated (the Configuration class itself is a component)
    • @Configuration(proxyBeanMethods = true)
      • ProxyBeanMethods Methods of the proxy bean. Default is True
      • When (proxyBeanMethods=true), no matter how many times an external component registration method is called in the configuration class, it gets the previously registered (singleton) object in the container.
      • ProxyBeanMethods =true Resolve component dependency issues
      • ProxyBeanMethods =false will skip the check and increase the speed
    • You can think of it as the (beans tag) in XML
  • @bean adds components to the container
    • (@bean) is used to (add components to the container), and the added components are (single instance)
    • @bean is annotated on the method of the class
    • Can be understood as (bean tag) in XML
  • process
    • @Configuration + @Bean + @Autowired
    • 1. Register: @Configuration + @Bean to inject components into the container
    • 2. Use @autowired to inject components into classes for use
/** * 1. @configuration class * 2. In the configuration class, use the @bean annotation to register the component to the container on the method. By default, the registered component is also a single instance * 3. Note: @configuration () @config () @config () @config () @config () @config () @config () * * Default is true * Full(proxyBeanMethods = true) singleton, Can be used for (component dependencies) * Lite(proxyBeanMethods = false) */ // tell SpringBoot that this is a (configuration) class, @configuration (proxyBeanMethods = true) public class UserConfig {// @bean // @bean Add component to container // 1. Return type is component type => UserBean // 3. @bean ("userX") public UserBean user01() {return new UserBean("woow_wu7", 20); }}Copy the code

(4.2) @autowired and @Resource and new

  • @Autowired
    • @autowired, @autowired, @autowired
    • @Autowired (Assembly by type) (singleton) (created when the program starts)
  • @Resource
  • @autowired vs. New
    • Autowired: Is an object created by Spring, (singleton), (scope is the entire project), and the project is created as soon as it starts
    • New: is to manually generate an instance object, (multiple cases), each call to generate a new object
  • process
    • @Configuration + @Bean + @Autowired
    • 1. Register: @Configuration + @Bean to inject components into the container
    • 2. Use @autowired to inject components into classes for use

@ Import and @ Bean (4.3)

  • @import applies to classes, which can be configuration classes, container classes such as Controller Service, etc
  • @import adds components to the container, similar to @bea
  • @Configuration + @bean is usually used together

(3) Hot update

  • 1. Introduce the spring-boot-devTools package
  • 2.Setting = > Build, Execution, Deployment = > Compiler = > hook on the Build project automaticallly
  • 3.command + 3 Callsactions, and then searchRegistry
  • 4. Check thecompiler.autoMake.allow.when.app.running
<! -- Spring-boot-devtools hot update --> <! -- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency>Copy the code

(4) Connect to the database to realize CRUD

  • Focus on the XML configuration of MyBatis
  • When adding, deleting, or updating, the return value is an Integer of type 1 for success and 0 for failure
  • You can configure @mapPerscan in the entry class so you don’t have to add @mapper to every Interface

(4-1) Install the mysql database to the server and connect to the database through Navicat Premium

  • MAC installation – Free Community version – bottom -MySQL Community Server
  • Mysql Installation tutorial for Windows version
  • Mysql common commands tutorial
  • Mysql > Select * from ‘navicat’;
    • Connecting to the databaseMysql -h Host address -u user name -p User password
    • Connecting to the databaseMysql -h 120.53.220.141 -u root -p
    • exitexit
    • Viewing the databaseshow databases;
    • Creating a databaseCreate database Database name;
    • Deleting a databaseDrop Database Database name;
    • Using a database Use Database name;
    • View the database currently in use select database();
    • See the tableshow tables;
    • Create a tableCreate table name (dDE column name type);
    • Delete tableDroop table name;
    • Display table structure Desc table name;
    • Mysqladmin -uroot -p123456 password 12345678;
    • Change password -p12345 is the current database password, and password is the database password to be set
    • View the installation path of the database show variables like "%char%";
    • Mysql > select * from ‘mysql’ where ‘mysql’ = ‘mysql’;
      • 1. If the database is connected, run the select version() command.
      • 2. If the CMD database is not connected, switch to the bin directory of the mysql database and run the mysql -v command
  • Download to your local environment

  • Connection, this is the remote server

(4-2) Add the required Maven dependencies

  • Need to bemysql-connector-java
  • Need to bespring-boot-starter-jdbc
  • Need to bemybatis-spring-boot-starter
<! Mysql -> <! -- mysql, version must be the same as the version you installed --> <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 8.0.24 < / version > < / dependency > <! -- JDBC dependency --> <! -- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc --> <dependency> < the groupId > org. Springframework. Boot < / groupId > < artifactId > spring - the boot - starter - JDBC < / artifactId > < version > 2.4.5 < / version > </dependency> <! -- mybatis dependent --> <! -- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> < the groupId > org. Mybatis. Spring. The boot < / groupId > < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.3 < / version >  </dependency>Copy the code

(4-3) Configure the data source component configuration items in Application.properties

Application.properties ------- # define datasource component # deprecation spring.datasource. Driver-class-name = com.mysql.jdbc.driver # note Spring. The datasource. Url = "JDBC: mysql: / / localhost: 3306 / database name? Time zone information: Or complains # are respectively (url) database (database driver) (user name) (password) spring. The datasource. Url = JDBC: mysql: / / localhost: 3306/7 - community - Java? serverTimezone=GMT%2B8&useSSL=false spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=rootCopy the code

(4-4) annotation method – Using myBatis annotation method to operate the database

  • In the pit of
    • The name of the entry main class must be correct, otherwise the mapper dependency cannot be found in server
    • The type in the mapper file, remember to select interface

(4-5) XML mode – Using myBatis XML mode to operate the database (emphasis)

  • The XML approach is more recommended for larger projects, as it is more powerful and flexible
  • The first step
    • Create a new mybatis folder in the Resources folder
    • Create a new one in the myBatis foldermybatis-config.xmlGlobal configuration file
      • mybatis/mybatis-config.xml
      • Mubatis
      • advice<configuration>The represented configuration is inapplication.ymlTo configure
    • Create a new one in the myBatis foldermapperFolder, then create insidemusicMapper.xmlMapper SQL mapping file
      • mybatis/mapper/musicMapper.xml
      • Inside write add delete change check code
      • My previous post
  • The second step
    • inresources.ymlTo configure myBatisGlobal configuration fileMapper SQL mapping fileThat is, specify the global configuration file location and SQL mapping file location of MyBatis
      • The config – location: the classpath: mybatis/mybatis – config. XML # mybatis global configuration file
      • Mapper – locations: the classpath: mybatis mapper / *. XML # mybatis SQL mapping file
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="com.example.demo.mapper.MusicMapper"> <! -- namespace is mapper file in mapper folder --> <! -- public abstract List<MusicBean> getMusic(); -- > <! -- id is the method name --> <! -- resultType is the return value type of the method, Through the copy path = > copy can be generated fast by reference -- > < select id = "getAllMusic resultType" = "com. Example. Demo. Beans. MusicBean" > select * from music </select> <select id="getMusic" resultType="com.example.demo.bean.MusicBean"> SELECT * FROM music WHERE name=#{name} </select> <insert id="addMusic" parameterType="com.example.demo.bean.MusicBean"> insert into music (name, singer) values (#{name}, #{singer}) </insert> <delete id="deleteMusic" parameterType="Integer"> delete from music where id=#{id} </delete> <update id="updateMusic" parameterType="Map"> update music set name=#{musicBean.name}, singer=#{musicBean.singer} where id=#{id} </update> </mapper>Copy the code
mapper


 public List<MusicBean> getAllMusic();

 public MusicBean getMusic(Integer id, String name);

 public Integer addMusic(MusicBean musicBean);

 Integer deleteMusic(Integer id);

 Integer updateMusic(Integer id, MusicBean musicBean);
Copy the code

(5) HandlerInterceptor

  • HandlerInterceptor
    • PreHandle executes before the target method executes, that is, before the target method executes in the controller
    • PostHandle executes after the target method executes (after completion)
    • AfterCompletion is executed after the page has been rendered
  • My previous post – Interceptors

(5-1) The specific implementation process of the interceptor

  • interceptor
    • 1. Create a new interceptor folder, then create a new musicInterceptor.java file
    • 2.public class MusicInterceptor implements HandlerInterceptor
    • 3. Create methods such as preHandler and write interception logic in them. Return true permits, return false indicates interception
  • config
    • 1. Create a config folder, then create an implementation class adminwebConfig.java file
    • 2.public class AdminWebConfig implements WebMvcConfigurer
    • 3.registry.addInterceptor(new MusicInterceptor())
    • 4..addPathPatterns("/**")// Intercept => Intercept all requests, including static resources
    • 5..excludePathPatterns("css/**")// The static CSS resources in the static folder are released

(6) Static resources

  • resources/static
  • resources/public
  • resources/MATA-INF/resources
  • resources/resources
  • The files in the above four folders are static resources that can be accessed byWith the path/static resource nameCan be
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @restController public class TestStaticResources {// Static resources/ / 1 // - resources/static // - resources/public // - Resources/mata-INF /resources // -resources // -resources // -resources // -resources // -resources // -resources // -resources // /** // Static map /** // request comes in, go to (controller) to see if it can handle, if it can't handle (static resource handler) to handle static resource. What happens if we have an interface /mm.jpg in our Controller and we also have a static resource called mm.jpg in our static resources folder? Spring.mvc.static-path-pattern =/ /resources/** // Resources /** // Resources /** // resources/** // resources/** / Current project + prefix + static resource HTTP: / / http://localhost:7777/resources/66.jpg / / 5 / / specifying custom static resource directory / / static folder path (the default) spring.web.resources.static-locations=[classpath:/7resources/] @GetMapping("/mm.jpg") public String getStaticResources()  { return "string, is not static resource mm.jpg"; }}Copy the code

(vii) File upload

Add (7.1)spring-boot-start-thymeleafMaven rely on

  • The main purpose of spring-boot-start-thymeleaf is to return HTML
<! -- spring-boot-starter-thymeleaf --> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>Copy the code

In (7.2)resources/templates/Create a new folderfileUpload.html

<! DOCTYPE html> <! - note: XMLNS :th="http://www.thymeleaf.org"> <meta charset=" utF-8 "> <meta name="viewport" Content ="width=device-width, initial =1.0"> <title>Document</title> </head> <div> <! -- th:action="@{/upload}" --> <! -- enctype="multipart/form-data" --> <form th:action="@{/upload}" method="post" enctype="multipart/form-data"> <div> <span style =" box-sizing: border-box! Important; word-wrap: break-word! Important; word-wrap: break-word! Important;" < div> <button type="submit"> </button> </form> </body> </html>Copy the code

New controller (7.3)

@Controller @Slf4j public class FileUploadController { @GetMapping("/fileUpload") public String handleFile() { return "fileUpload"; } @PostMapping("/upload") public String upload( @RequestPart("single") MultipartFile single ) throws IOException { if (! single.isEmpty()) { String originalFilename = single.getOriginalFilename(); // get the originalFilename log.info("{}", originalFilename); } return "fileUpload"; }}Copy the code