Tag Archives: spring boot

[Solved] Error resolving template template might not exist or might not be accessible

Resolving error template template may not exist or may not be accessible

    1. there may be a problem with your controller annotation
    1. the difference between controller annotation and restcontroller annotation. Thymeleaf configures the corresponding path in the properties or YML configuration file
    1. about

      1. properties spring.web.resources.static-locations=classpath:/static/, classpath:/templates/ yml
	spring:
      thymeleaf:
        # thymeleaf The directory where the page is stored
        prefix: classpath:/templates/

Return path problem
there is no Maven clear in the return path

Caused by: org.springframework.beans.factory.beancreationexception: error creating be

Java packaging error:
caused by: org.springframework.beans.factory.beancreationexception: error creating bean with name ‘org.springframework.transaction.annotation.proxytransactionmanagementconfiguration’: initialization of bean failed; Needed exception is org.springframework.beans.factory.nosuchbeandefinitionexception: no bean named ‘org.springframework.context.annotation.configurationclasspostprocessor.importregistry’ available

click the picture to see that it is actually an error message from javamailsender. First, check whether the configuration file is configured to send mail

If the project is used with Nacos, check the local configuration file xxx.yml to see if the Nacos configuration is annotated. As shown in the following figure, if the annotation is, you can uncomment it.

Upload file error analysis standardmultiparthttpservletrequest

controller

/**
 * MultipartFile Automatic encapsulation of uploaded files
 * @param email
 * @param username
 * @param headerImg
 * @param photos
 * @return
 */
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
                     @RequestParam("username") String username,
                     @RequestPart("headerImg") MultipartFile headerImg,
                     @RequestPart("photos") MultipartFile[] photos) throws IOException {

    log.info("Upload the message:email={},username={},headerImg={},photos={}",
            email,username,headerImg.getSize(),photos.length);

    if(!headerImg.isEmpty()){
        String originalFilename = headerImg.getOriginalFilename();
        headerImg.transferTo(new File("D:\\cache\\"+originalFilename));
    }

    if(photos.length > 0){
        for (MultipartFile photo : photos) {
            if(!photo.isEmpty()){
                String originalFilename = photo.getOriginalFilename();
                photo.transferTo(new File("D:\\cache\\1"+originalFilename));
            }
        }
    }


    return "main";
}

Common errors:

New file (“D: \ cache \ 1” + originalfilename “), there is no duplicate disk file name

Debug the debug mode and enter the transferto method. It is found that the source code is to judge whether the file exists

debug mode evaluate expression. Open the expression debugging window and see the error

Failure of spring boot configuration server port

Problem Description: do not go to the port configured by yourself after the project is started?Just go 8080

Solution 1

Please check whether there is any in the target file after packaging   Application profile

  If not, add the following code to the POM file

         <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>mapper/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

Solution 2

        Check whether the configuration file format is aligned, whether there are redundant spaces, etc

[Solved] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on

This problem bothered me for a while. What I want to say is that I couldn’t find the problem when deploying springboot through Maven. Therefore, after quickly arranging a springboot project, I found that the error will still be reported

So I looked at this version number and added it in and it worked
   <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.3</version>
            </plugin>
        </plugins>
    </build>

Defining a bean of type ‘org.springframework.data.redis.core.RedisTemplate‘ in your configuration.

The spring-boot integration redis startup project reports an error with the following message:
defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.
orConsider defining a bean of type 'org.springframework.data.redis.core.StringRedisTemplate' in your configuration.
Modify the pom file
Change the

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

is changed to

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

After modification, if you want to customize redistemplate, you can refer to the following configuration


    @Bean
    public RedisTemplate<String, Object> template(RedisConnectionFactory factory) {
        // Create RedisTemplate<String, Object>object
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // Configuring the connection factory
        template.setConnectionFactory(factory);
        // Define the Jackson2JsonRedisSerializer serialization object
        Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        // Specify the field, field, get and set to be serialized, and the range of modifiers, ANY of which are included in private and public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // Specify the type of serialized input, the class must be non-final modified, final modified class, such as String, Integer, etc. will report an exception
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        jacksonSeial.setObjectMapper(om);
        StringRedisSerializer stringSerial = new StringRedisSerializer();
        // redis key Serialization method used stringSerial
        template.setKeySerializer(stringSerial);
        // redis value Serialization method usedjackson
        template.setValueSerializer(jacksonSeial);
        // redis hash key Serialization method usedstringSerial
        template.setHashKeySerializer(stringSerial);
        // redis hash value Serialization method usedjackson
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

Error creating bean with name ‘feignTargeter‘ defined in class path resource [org/springframework/cl

Specific error information:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'feignTargeter' defined in class path resource [org/springframework/cloud/openfeign/FeignAutoConfiguration$DefaultFeignTargeterConfiguration.class]: Initialization of bean failed; nested exception is java.lang.IllegalAccessError: class org.springframework.cloud.openfeign.$Proxy207 cannot access its superinterface org.springframework.cloud.openfeign.Targeter
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
	at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$148/267257399.getObject(Unknown Source)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
	at com.ruoyi.RuoYiApplication.main(RuoYiApplication.java:21)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalAccessError: class org.springframework.cloud.openfeign.$Proxy207 cannot access its superinterface org.springframework.cloud.openfeign.Targeter
	at java.lang.reflect.Proxy.defineClass0(Native Method)
	at java.lang.reflect.Proxy.access$300(Proxy.java:228)
	at java.lang.reflect.Proxy$ProxyClassFactory.apply(Proxy.java:642)
	at java.lang.reflect.Proxy$ProxyClassFactory.apply(Proxy.java:557)
	at java.lang.reflect.WeakCache$Factory.get(WeakCache.java:230)
	at java.lang.reflect.WeakCache.get(WeakCache.java:127)
	at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:419)
	at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:719)
	at com.alibaba.cloud.dubbo.openfeign.TargeterBeanPostProcessor.postProcessAfterInitialization(TargeterBeanPostProcessor.java:75)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:430)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1798)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
	... 21 common frames omitted

Analysis reason:

First of all, the project does not configure openfeign, but uses Dubbo, but why report the error of openfeign?Secondly, during initialization   There is an error in the configuration class of openfeign. It can be seen from this that the construction must be started by default. Now that you know the direction, go to see if there are openfeign packages in the imported packages, as follows:   Really, would it be good to remove the openfeign package?It’s OK to try. The problem is solved

  terms of settlement:

Exclude the package of openfeign. Note here that the spring cloud openfeign core package or the automatic loading of openfeign configuration in the startup class are excluded, as follows:

@SpringBootApplication(exclude = { FeignAutoConfiguration.class })

 

The spring boot project directly replaces the referenced jar package

Shiro was used in an old spring boot project. Recently, Shiro broke a security vulnerability. So we need to upgrade the Shiro version in the project. However, this project was developed by former employees a long time ago, and the source code can no longer be found. So try to upgrade Shiro by replacing jar directly.

Wrong attempt

Usually, HTML can be replaced directly. JS can directly open WinRAR and replace the file directly. I thought jar packages can also be replaced directly. If you find that the jar is directly replaced, an error will be reported.

The error information is as follows:

java -jar spring-zs-1.0-update.jar                                                          [18:02:05]
Exception in thread "main" java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/shiro-web-1.5.3.jar'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file
	at org.springframework.boot.loader.jar.JarFile.createJarFileFromFileEntry(JarFile.java:285)
	at org.springframework.boot.loader.jar.JarFile.createJarFileFromEntry(JarFile.java:260)
	at org.springframework.boot.loader.jar.JarFile.getNestedJarFile(JarFile.java:248)
	at org.springframework.boot.loader.jar.JarFile.getNestedJarFile(JarFile.java:237)
	at org.springframework.boot.loader.archive.JarFileArchive.getNestedArchive(JarFileArchive.java:103)
	at org.springframework.boot.loader.archive.JarFileArchive.getNestedArchives(JarFileArchive.java:87)
	at org.springframework.boot.loader.ExecutableArchiveLauncher.getClassPathArchives(ExecutableArchiveLauncher.java:72)
	at org.springframework.boot.loader.Launcher.launch(Launcher.java:49)
	at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

Correct steps

Unpack through jar command

My project jar name is spring-zs-1.0. Jar

jar -xvf spring-zs-1.0.jar

After decompression, replace the jar package in./boot-inf/lib directory. I replaced Shiro — 1.2.2.jar with Shiro — 1.5.3.jar

Repackage

jar -cfM0 new.jar ./

This will generate a new jar package!

If you also use MacOS system, you should pay attention to one thing. The MacOS system will automatically generate
. DS in some directories_ Store files, so you should delete these hidden. DS files before repackaging_ Store, otherwise an error will be reported.

reference resources

https://blog.csdn.net/weixin_ 45417347/article/details/101539040

[Solved] java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

Project scenario:

Spring boot project, user-defined filter, intercept requests and process business.


Problem Description:

When you start the project access interface, you call resp.sendRedirect () in the custom filter.


Cause analysis:

After the response has been submitted, the sendredirect() method cannot be called.

In fact, chain. Dofilter (req, resp) is executed; Cannot use sendredirect() of resp object after

So looking at the code, we find that:

...

  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;
  ....
  boolean flag = getStatus();
  if (flag) {
      ....
      chain.doFilter(request, response);
  }
  httpResponse.sendRedirect(“xxxx”);
...

if the judged flag is true, chain.dofilter (request, response) will be executed, and httpresponse.sendredirect (“XXXX”) </ font> will be executed after execution


Solution:

After chain. Dofilter (request, response), add return to end the current method.

...

  HttpServletRequest httpRequest = (HttpServletRequest) request;
  HttpServletResponse httpResponse = (HttpServletResponse) response;
  ....
  boolean flag = getStatus();
  if (flag) {
      ....
      chain.doFilter(request, response);
      return;
  }
  httpResponse.sendRedirect(“xxxx”);
...

Solve the problem of springboot and unit test starting applicationrunner

During the execution of unit test, applicationrunner was started unexpectedly, resulting in the initialization of netty server and the failure of unit test execution.

Solution: by setting the profile of bean corresponding to applicationrunner

Add notes to corresponding components:

@Profile(“! test”)

Add notes to unit tests:

@ActiveProfiles(“test”)

Spring boot does not take effect when using @ size to verify a single set parameter of the control layer

Spring boot does not take effect when using @ size to verify a single set parameter of the control layer

1. Problem description

In the figure below, there is a type of List & lt; String> method parameter, when using @ size to mark the verification quantity, it is found that no exception is thrown

2. Solution

You need to add the @ validated annotation on the control class, and restart the project

Exception handling of httpmessage notwritableexception in springboot

preface:

First, post the error report log

Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.test.dto.ResultBean]

If the log is similar, you can continue to look down.

1. Causes and Solutions

Restore the accident scene first (only show the core problem code)

Interface layer code:

@RestController
@RequestMapping("/client")
public class ControllerTest {

    @GetMapping("/test")
    public ResultBean name() {
        return ResultBean.success();
    }
}

ResultBean Code:

public class ResultBean {

    private String code;
    private String result;

    ResultBean(String code, String result) {
        this.code = code;
        this.result = result;
    }

    public static ResultBean success() {
        return new ResultBean("200", "success");
    }

}

The error log points to this   ResultBean. The big probability is that there is a problem with this bean. After careful analysis of the log, it probably means that it is impossible to get the value, so it is impossible to write. Get the value?Get method?It seems that ResultBean is missing the get method (Lombok annotation is forgotten). With the get method, the problem is solved

Tips: be sure to add get and set methods and try to write by hand; Lombok annotations are rarely used. There are holes in them. Occasionally, the default method for generating special fields cannot be recognized by other components.