Campus recruitment summary

Create a springboot project

Compilation knowledge

1. target

If mapper If the XML file is not included in the target, it should be added in the build first, and then the clean Maven project should be compiled again

 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

In the project

1. @RequestBody

Because it is a front-end and back-end separated item, the data transmitted is generally in the form of json, string and integer. You need to add @ RequestBody to the transmitted parameters and the return value is also json


2. hibernate-validator

https://blog.csdn.net/qq_32258777/article/details/86743416

During development, you often need to write some field verification codes, such as non empty field, field length limit, mailbox format verification, etc. writing these codes that have little to do with business logic has two troubles:

  • The verification code is cumbersome and repetitive
  • The code inside the method is verbose
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

3. Login

3.1 principle


3.1.1 set the token and store it in redis

  • First, compare the user name and password, then log in successfully, set the token, and store the token in redis (if the redis uses Lettuce as thread safe, the expiration time will be set)

####3.1.2 setting interceptors

  • Set the interceptor and put the token into the request header (this token is the value taken from reids)
    • If a token is carried in the request header and redis contains this token, reset the expiration time
    • Otherwise, if there is no problem, a TokenException will be thrown. Because the problem is not thrown well, @ ControllerAdvice will sort out the problem

Configure interception, except for / login

There is no token thrown in the header

After the TokenException is thrown, format the problem into json

3.1.3 type verification

  • If the login user is a student and has obtained the token, the function menu returned by the front end. However, if the student has guessed the website of admin/create and carried the token, he can access the website. Based on this situation, the type needs to be verified

  • Control by transaction

Transaction control

Custom permission error

Bad permission json

3.1.4 local thread

The purpose is to prevent illegal access. For example, if you know the website, you can access it with a token, but the type may be wrong, that is, illegal access

TokenInterceptor content

Join TokenInterceptor to enter global webmvcconfigurer global view configuration

3.2 spring boot integration Redis

Both lattice and Jedis are clients connected to RedisServer

Lettuce: SpringBoot2. After X, lettue, scalable and thread safe will be used by default

Jedis: Spring1.5.x uses jedis by default; Multithreading environment is non thread safe

1) Introduce related dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2) Configure application YML file

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/job?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
  redis:
    host: 127.0.0.7
    port: 6379
    database: 0
    password:
    lettuce:
      pool:
        max-active: 10
        min-idle: 0
        max-wait: -1ms
        max-idle: 8
  1. Configure RedisTemplate
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory connectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        //1. Resolve key serialization
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //2. Resolve value serialization
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

}

4) General Redis tool class

See code for details

3.2.1 redis serialization and deserialization

3.2.1.1 serialization

Objects must be serialized before they can be stored

3.2.1.2 deserialization

If it is not deserialized, the storage format is hexadecimal, and the value is also garbled

Both GenericJackson2JsonRedisSerializer and Jackson2JsonRedisSerializerdo can be used to serialize and deserialize non generic array objects normally

If the stored type is List and other objects with generic types, the serialization method of Jackson2JsonRedisSerializer will report an error during deserialization, while the deserialization method of GenericJackson2JsonRedisSerializer is successful

1. To use Jackson2JsonRedisSerializer, you need to specify the serialized Class. You can use obejct Class

2. Using GenericJacksonRedisSerializer is less efficient and takes up more memory than Jackson2JsonRedisSerializer.

3. The GenericJacksonRedisSerializer deserializes the array class with generics and reports a conversion exception. The solution is stored as a JSON string.

4. Both GenericJacksonRedisSerializer and Jackson2JsonRedisSerializer store data in JSON format, which can be used as the serialization method of Redis.

4. Cross domain issues

Due to the separation of front and back ends, cross domain problems occur when different ports are requested

4.1 solving cross domain problems with CorsFilter

package com.jiang.framework.mvc;

import org.springframework.web.filter.CorsFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class GlobalWebMvcConfigurer implements WebMvcConfigurer {

    @Bean
    public TokenInterceptor tokenInterceptor() {
        return new TokenInterceptor();
    }

    // Configure interception
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login"); // Block all except login
    }

    @Bean
    // Solving cross domain problems with CorsFilter
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // Domain names that allow cross domain requests
        corsConfiguration.addAllowedOrigin("*");
        // Methods to allow cross domain requests
        corsConfiguration.addAllowedMethod("*");
        // Allow any head
        corsConfiguration.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        CorsFilter corsFilter = new CorsFilter(corsConfigurationSource);
        return corsFilter;
    }
}

  • /**It means all folders and subfolders inside
  • /*Is all folders without subfolders
  • /Is the root directory of the web project

5. Industry management tree


Backend build tree


6. Date issue

6.1 vue display problems

In vue, the back end is date, and then json returns a date format. When displayed, it is a string in the form of date, which can be displayed in applocation Processing in XML

6.2 elementui El picker date problem

When getting the date, it is always one day away from the selected date, which can be solved through the front and back ends

application.xml file


7. File upload

7.1 front end

First, the front end is implemented through the elementUi component

7.2 back end


8 use of local threads


9. sql condition query

Unfamiliar sql statement

10. Processing of hot articles (real-time ranking)

Processing through redis

When the article is clicked once, the reading number is increased by 1, and then the reverse range byscore is used to reorder to get the highest ranking. However, it still feels that the efficiency is not high. It should feel that when the reading volume reaches a certain value, it can be filtered. When it reaches a certain value, it can be filtered by taking more than a value, because there are only a few hot spots.

10.1 setting articles

10.2 rank the top 10 articles

  • reverseRangeByScore: returns an ordered combination of all members in the specified score range, arranged in descending order

vuejs

1. router

Write router to access / user

  1. Citation problem

2. Slot handling

3. Login routing processing

Because there are three different login types, the user will carry the corresponding type when logging in. When the login page is not refreshed, there will be no permission

Therefore, you need to refresh the page first, that is, call the route again

For subsequent tokens, if there are still tokens in memory, the login will still be wrong, so you need to refresh the tokens in memory

elementUi

Keywords: Java Mybatis Spring

Added by Malkavbug on Fri, 14 Jan 2022 00:18:32 +0200