Category Archives: JAVA

How to Solve RAR Files Extract Error with sevenzipjbinding (Multithread Processing)

1. Question

Recently, I encountered a problem in the development process. Use sevenzipjbinding to extract the file and report error: SevenZipJBinding wasn’t initialized successfully last time

Use a simple case to repeat it. Note: after the program is started for the first time, the decompression method will appear when multiple threads execute decompression at the same time

@RestController
@RequestMapping("/test")
@Slf4j
public class TestContortller {

    @GetMapping("/unRar")
    public void unRar() {
        String source = "D:\\temp\\test.rar";
        String target = "D:\\temp\\test\\";
        new Thread(() -> unRar(source, target + Thread.currentThread().getId())).start();
        new Thread(() -> unRar(source, target + Thread.currentThread().getId())).start();
        new Thread(() -> unRar(source, target + Thread.currentThread().getId())).start();
    }

    public static void unRar(String source, String target) {
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(source, "r");
             IInArchive archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile))) {
            int[] in = new int[archive.getNumberOfItems()];
            for (int i = 0; i < in.length; i++) {
                in[i] = i;
            }
            archive.extract(in, false, new ExtractCallback(archive, target));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

2. Cause

Checking the sevenzipjbinding source code, we find that when calling the decompression method, we first determine whether initialization is needed. autoInitializationWillOccur defaults to true, and when the first thread comes into this method, autoInitializationWillOccur is changed to When the first thread comes in this method, autoInitializationWillOccur will be changed to false, and then initialize the relevant dependencies (this operation takes some time), at this time other threads come in this method, autoInitializationWillOccur has changed to false and no longer initialize, but because the first thread has not completed the initialization operation initializationSuccessful is still is false, so it will throw the SevenZipJBinding wasn’t initialized successfully last time exception

3. Solution

You can use ApplicationRunner to automatically execute the initSevenZipFromPlatformJAR method after the program is started, to first initialize the dependencies needed for sevenzipjbinding.

@Component
public class InitService implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        SevenZip.initSevenZipFromPlatformJAR();
        log.info("Initialize sevenzipjbinding related dependencies complete!");
    }
}

[Solved] Springboot Project Startup Error: Unable to Identify bootstrap.yml Configuration

Question

The springboot project I built myself reports an error when I start the project, but I can’t find the relevant configuration information. It is clearly configured in bootstrap.yml , and the application.yml I have been using before. Thinking that the priority of application.yml is not as high as that of bootstrap.yml, the bootstrap configuration file is definitely fine. , the result is that the project can’t live or die.

reason
The SpringBoot project will only recognize application.* configuration files, and will not automatically recognize bootstrap.yml.
The bootstrap.yml configuration is only used in the SpringCloud project. If you want to use the bootstrap.yml in the springboot project, then you need to add the bootstrap starter.

Add bootstrap initiator

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

Since SpringCloud is built on SpringBoot, all SpringCloud projects are identified by both kinds of files, and it is only at this time that there is a priority statement that SpringCloud projects are given priority to read bootstrap configuration in reading application configuration.
SpringCloud applications are run based on the context of bootstrap.

[Solved] Windows Start RocketMq Error: Unrecognized VM option ‘UseCMSCompactAtFullCollection‘

Rocketmq download address: downloading the Apache rocketmq releases – Apache rocketmq

Environment

system windows 10 64 bit
jdk version jdk11
RocketMQ version 5.0

question:

After downloading, unzip the package and start the cmd file, the following error message appears:

Solution:
1. Change the jdk version to below 9. Versions 9 and above are obsolete CMSCompactAtFullCollectionand cannot be supported.

2. Delete parameters not supported by jvm: open runserver.cmd to edit; or comment out this line.

There may be other unsupported classes: PrintGCDateStamps, PrintGCTimeStamps, etc. are all handled this way.

Unrecognized VM option ' <Option> '
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

There is also a list of 50 options that no longer work in JDK 9. Check that you are using these options on the command line and in the startup script:

  • AdjustConcurrency
  • CMSCompactWhenClearAllSoftRefs
  • CMSDumpAtPromotionFailure
  • CMSFullGCsBeforeCompaction
  • CMSIncrementalDutyCycle
  • CMSIncrementalDutyCycleMin
  • CMSIncrementalMode
  • CMSIncrementalOffset
  • CMSIncrementalPacing
  • CMSParPromoteBlocksToClaim
  • CMSPrintEdenSurvivorChunks
  • CollectGen0First
  • GCLogFileSize
  • NumberOfGCLogFiles
  • ParallelGCVerbose
  • PrintAdaptiveSizePolicy
  • PrintCMSInitiationStatistics
  • PrintCMSStatistics
  • PrintClassHistogramAfterFullGC
  • PrintClassHistogramBeforeFullGC
  • PrintFLSCensus
  • PrintFLSStatistics
  • PrintGCApplicationConcurrentTime
  • PrintGCApplicationStoppedTime
  • PrintGCCause
  • PrintGCDateStamps
  • PrintGCTaskTimeStamps
  • PrintGCTimeStamps
  • PrintHeapAtGC
  • PrintHeapAtGCExtended
  • PrintJNIGCStalls
  • PrintOldPLAB
  • PrintPLAB
  • PrintParallelOldGCPhaseTimes
  • PrintPromotionFailure
  • PrintReferenceGC
  • PrintTLAB
  • PrintTenuringDistribution
  • TraceDynamicGCThreads
  • TraceGen0Time
  • TraceGen1Time
  • TraceMetadataHumongousAllocation
  • TraceParallelOldGCTasks
  • UseCMSCollectionPassing
  • UseCMSCompactAtFullCollection
  • UseGCLogFileRotation
  • UseMemSetInBOT
  • UsePPCLWSYNC
  • UseVMInterruptibleIO
  • WorkAroundNPTLTimedWaitHang

[Solved] JAVA Web Error: startup failed due to previous errors

1. Error prompt:

WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more Filters failed to start. Full details will be found in the appropriate container log file
WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [/filter] startup failed due to previous errors

File directory structure:

After testing, we found that there is a problem with the configuration in the web.xml file, and the parameter names configured are not the same as those obtained in the filter, resulting in a startup error

2. Solution

Correct the configured parameters and republish them

[Solved] Docker Run Tomcat Error: Cannot find /usr/local/tomcat/bin/setclasspath.sh

Docker reports an error when running Tomcat

Cannot find /usr/local/tomcat/bin/setclasspath.sh
This file is needed to run this program

After trying, use the add command packaged with dockerfile

RUN unset CATALINA_HOME

Invalid after attempt

The prompt is that setclasspath.sh cannot be found, because this Tomcat restarts repeatedly

So use the command to copy a bin directory to the current folder

docker cp Docker_id:/usr/local/tomcat/bin ./

The result shows that setclasspath.sh exists, so where is the problem? Look for the error reporting code

In the catalina.sh script, the part causing the problem is as follows:


  if [ -r "$CATALINA_HOME"/bin/setclasspath.sh ]; then
    . "$CATALINA_HOME"/bin/setclasspath.sh
  else
    echo "Cannot find $CATALINA_HOME/bin/setclasspath.sh"
    echo "This file is needed to run this program"
  fi

The square brackets plus the -r command means to test whether the file is read-only. Similarly, – x tests whether the file is executable

In the problematic system, the – R command call in the container is abnormal.

Try to start a temporary tomcat8 authentication,

docker run -it --rm --entrypoint=/bin/bash tomcat:8

Note: executing the docker run command with the –rm command option is equivalent to executing docker rm -v after the container exits
execute command

root@f338debf92f6:/usr/local/tomcat# [[ -r /bin/bash ]]
root@f338debf92f6:/usr/local/tomcat# echo $?
1

Executed on a normal system

root@0083a80a9ec2:/usr/local/tomcat# [[ -r /bin/bash ]]
root@0083a80a9ec2:/usr/local/tomcat# echo $?
0

The command ‘$?’ indicates the exit status of the previous command or the return value of the function
for exit status, 0 indicates no error, and any other value indicates an error. In general, most commands return 0 upon successful execution and 1 upon failure. Some commands return other values, indicating different types of errors.

How to solve it
this is related to the faccessat2 system call. Due to the bug in runc, if your kernel does not support faccessat2, it will fail. There is an article saying that upgrading the kernel to 5.8 or above may work well, but I have tried it hard, because the kernel with the problem is 5.10
Method 1: update runc >= 1.0.0-rc93

Method 2: — privileged switch to run the container

Specific implementation of method 1:

View the original runc version

runc -v

Download version 1.0.0-rc95 of runc.amd64

Download address: releases · opencontainers/runc · GitHub

Name change and Execution Authority

mv runc.amd64 runc && chmod +x runc

View and back up the original runc

whereis runc

Some systems are in the /usr/bin/ directory, some systems are in the /usr/local/bin/ directory, the following commands are in the /usr/local/bin/ directory, the following commands are in the /usr/bin/ directory, change the directory yourself

mv /usr/local/bin/runc /usr/local/bin/runcbak

Overwrite the original runc

cp runc /usr/local/bin/runc

View the new version of runc

runc -v

Restart docker

systemctl restart docker

Method 2: concrete implementation

Docker run execution

docker run --privileged=true -p 8080:8080 tomcat:8

Add in docker-compose.yml

version: '2'
services:
    tomcat:
     container_name: tomcat
     image: tomcat:8
     ports:
         - '8080:8080'
     environment:
         - TZ=Asia/Shanghai
     privileged: true
     restart: always

[Solved] Python Error: socket.error [Errno 9] Bad file descriptor

To learn Python Network programming, I wrote two small programs on the server and the client according to the book, and found that an error was reported:

Traceback (most recent call last):

File “./tsTserv.py”, line 20, in

data = tcpCliSock.recv(BUFSIZ)

File “/usr/lib/python2.6/socket.py”, line 165, in _dummy

raise error(EBADF, ‘Bad file descriptor’)

socket.error: [Errno 9] Bad file descriptor

The source code of the server side is as follows:

while True:
        print 'waiting for connection...'
        tcpCliSock,addr = tcpSerSock.accept()
        print '...connected from:',addr
        while True:
                data = tcpCliSock.recv(BUFSIZ)
                if not data:
                        break
                tcpCliSock.send('[%s] %s' %(ctime(),data))
        tcpCliSock.close()
tcpSerSock.close()

Solution:

tcpCliSock.close() is placed in the second while loop, causing tcpCliSock to be closed after receiving data once, and this statement should be placed in the outer loop

[Solved] Cannot call sendError() after the response has been committed

Background of error reporting: when working on the open source project “Ruiji takeout”, after writing the interceptor code, when the front-end logs in, the back-end reports an error as follows:

        

 

Solution:

I found that my code, at the very beginning of the method, has unconditionally released any resources, i.e. filterChain.doFilter(request, response); when this line of code, and then continue to write the code to execute the response, it will report the above error. So, just comment out this line of code.

[Solved] Spring-MVC Error: org.springframework.validation.BeanPropertyBindingResult

The error report is as follows:

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object ‘shopOrder’ on field ‘orderTimePay’: rejected value [2019-01-13 12:05:00];

 

Reason & Solution:
SimpleDateFormat is non-thread-safe. It’s OK to get a new SimpleDateFormat() under each thread.

[Solved] error: invalid operands of types ‘QLabel*‘ and ‘void‘ to binary ‘operator>

Error in QT: invalid operators of types’ qlabel * ‘and’ void ‘to binary’ operator & gt; ‘ Wrong solution.

This kind of error is generally the operation symbol use error

For example:

btnLabel>setFixedSize(menuBtn->width(),menuBtn->height());

Here ‘>’ operation symbol is wrong, changed to ‘->’, it will be OK!

 btnLabel->setFixedSize(menuBtn->width(),menuBtn->height());

[Solved] Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of

Problem Description: my project was fine the day before yesterday. Suddenly, the following error was reported after opening it the next day

Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.16.

I didn’t use kotlin either. Finally, I recompiled the project when compiling

Done!

[Solved] Errorjava Compilation failed internal java compiler error

Error Messages:

Errorjava Compilation failed internal java compiler error

 

Solution:

1. view the project’s jdk (Ctrl+Alt+shift+S)
File ->Project Structure->Project Settings ->Project

2, view the project’s jdk (Ctrl+Alt+shift+S)
File ->Project Structure->Project Settings -> Modules -> (Name of the project to be modified) -> Sources ->

3. View Java configuration in idea
File ->Setting ->Build,Execution,Deployment -> Compiler -> Java Compiler

If the above three steps still fail
Clear IDEA cache Restart IDEA
File->Invalidate Caches/Restart

[Solved] Error resolving template [x] template might not exist or might not be accessible by any of the con

1. Recurrence problem

Today, after configuring Shiro + jwt , you can start spring boot normally. However, when calling the auth/login login method, the following error is reported:

2022-08-21 12:35:18.205 [ http-nio-8081-exec-1 ] - [ ERROR ] [ org.thymeleaf.TemplateEngine : 1136 ] - [THYMELEAF][http-nio-8081-exec-1] Exception processing template "auth/login": Error resolving template [auth/login], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [auth/login], template might not exist or might not be accessible by any of the configured Template Resolvers
	at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:869)
	at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607)
	at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
	at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)
	at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:366)
	at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:190)
	at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1396)
	at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1141)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:114)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:112)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
	at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
	at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
	at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
	at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
	at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:450)
	at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
	at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
	at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
	at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
	at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
	at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:204)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)

Why did this error occur?Let me analyze it step by step.

2. Analyze problems

2.1 check pom dependency

I have configured the following dependencies in the .pom file

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

This dependency is to configure the thymeleaf template engine, which we can use to design the template mail sent.

The above error message is sent by this dependency. Let’s see what the thymeleaf the template engine is?

2.2 detailed explanation of thymeleaf engine

thymeleaf Template Engine
thymeleaf is a modern server-side Java templating engine for web and standalone environments.
The main goal of thymeleaf is to bring elegant, natural templates to your development workflow – HTML that displays correctly in the browser and works as a static prototype, allowing for enhanced collaboration in development teams.
With modules for the Spring Framework, extensive integration with your favorite tools and the ability to plug in your own features, thymeleaf is ideal for modern HTML5 JVM web development – although it still has a lot of work to do.
thymeleaf has the following features.
thymeleaf runs with or without a network, so it can be opened directly in a browser to view static page effects. It supports HTML prototypes and can add other attributes inside HTML tags to enable data rendering.
thymeleaf has an out-of-the-box feature. thymeleaf is the recommended template engine for Spring boot and is displayed directly in html, so the front and back ends can be well separated.
It has the following references in spring boot.
internationalization : rendering different countries’ languages
common page display : such as unified exception page handling, common page handling

2.2 check YML configuration

I found that there is no configuration information of thymeleaf in application.yml. The problem may occur here. Therefore, the following configuration is performed in application.yml

spring:
  thymeleaf:
    cache: false 
    prefix: classpath:/templates 
    encoding: UTF-8 
    suffix: .html 
    mode: HTML 

Configuration Description:

  1. The cache line is to turn off the cache of the page, otherwise we may not see the changes in time after changing the page, the default is true.
  2. prefix is to configure the location of the thymeleaf template.
  3. encoding is to configure the encoding of the thymeleaf document.

In many cases, if thymeleaf dependency is introduced, the problem can be solved by configuring the above information in the YML file. If this cannot solve your problem, you can continue to read my analysis

But after I configured the above information in the application.yml file and spring boot is successfully started, calling the /auth/login method still reported the above error, so where does the problem lie?

3. Solve problems

After repeated breakpoint debugging, I found out where the problem was. Originally, it was in my unified exception handling. My source code is written as follows:

/**
 * @author baoya
 * @datetime 2022/8/10 21:50
 * @desc 
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = AuthenticationException.class)
    public ReturnResult incorrectCredentialsException(HttpServletRequest request, AuthenticationException e) {
        log.error("Incorrect username or password: {}, request interface: {}", e, request.getRequestURI());
        return ReturnResult.error(USER_CREDENTIALS_ERROR);
    }
}

Restart spring boot and call the /auth/login method and test with postman as follows.

/**
 * @author baoya
 * @datetime 2022/8/10 21:50
 * @desc 
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = AuthenticationException.class)
    public ResponseEntity<ReturnResult> incorrectCredentialsException(HttpServletRequest request, AuthenticationException e) {
        log.error("Incorrect username or password: {}, request interface: {}", e, request.getRequestURI());
        return buildResponseEntity(ReturnResult.error(USER_CREDENTIALS_ERROR));
    }

    /**
     * 
     */
    private ResponseEntity<ReturnResult> buildResponseEntity(ReturnResult apiError) {
        return new ResponseEntity<>(apiError, HttpStatus.valueOf(HttpStatus.BAD_REQUEST.value()));
    }
}

Restart the spring boot and call the /auth/login method. Use the postman test, as shown in the following figure: