Tag Archives: spring

How to Solve Springboot Error: Failed to convert value of type

Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘java.lang.Integer’; nested exception is java.lang.NumberFormatException: For input string: “50.5”]

General meaning:
failed to convert the value of type “Java. Lang. string” to the required type “Java. Lang. integer”; Nested exception is java.lang.numberformatexception: for input string: “50.5”]

This kind of error is usually caused by the parameters passed by the front end and the failure of the back end parsing, that is, it is wearing illegal parameters. For example, the upper front end gives me a floating point number, and the back end will fail when the string is parsed into a number!

[Solved] Java.lang.IllegalStateException: getReader() has already been called for this request

For the project, it is necessary to obtain the data in the request body in the interceptor for data verification, because the @ requestbody annotation is used in the self-defined controller, resulting in an error in the project. The content of the error is: Java. Lang. IllegalStateException: getreader() has already been called for this request

After consulting the data, it is found that the getReader and getinputstream in the request are obtained by stream. After reading once, they can’t be used again. The solution is:

Step 1: define a filter in which a self-defined request is passed in. The self-defined request inherits the wrapper class httpservletrequestwrapper and rewrites the getinputstream and getReader methods
the filter code is as follows:

package com.chinastock.filter;

import com.chinastock.util.CustomHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zhoule
 * @description: handle request
 */
public class IMTAFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new CustomHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        }
        if(requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }
}

The custom request code is as follows:

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author zhoule
 * @description: Custom request wrapper for processing messages in the request body
 */
public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private byte[] body;

    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException
    {
        super(request);

        BufferedReader reader = request.getReader();
        try (StringWriter writer = new StringWriter()) {
            int read;
            char[] buf = new char[1024 * 8];
            while ((read = reader.read(buf)) != -1) {
                writer.write(buf, 0, read);
            }
            this.body = writer.getBuffer().toString().getBytes();
        }
    }

    public String getBody(){
        return new String(body, StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException
    {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream()
        {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            public int read() throws IOException
            {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException
    {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}

The second step is to write the interceptor of the project. Some codes of the interceptor are as follows:

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
        String body = wrapper.getBody();
        System.out.println(body);
        return true;
    }

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;
    }

Failed to read artifact descriptor for com.google.errorprone:javac:jar:9+181-r4173-1

Build failure occurs when Java Maven project is executed.

Full text of error report:

[ERROR] Failed to execute goal com.microsoft.azure:azure-webapp-maven-plugin:1.12.0:config (default-cli) on project spring-petclinic: 
Execution default-cli of goal com.microsoft.azure:azure-webapp-maven-plugin:1.12.0:config failed: Plugin com.microsoft.azure:azure-webapp-maven-plugin:1.12.0 or one of its dependencies could not be resolved: 
Failed to collect dependencies at com.microsoft.azure:azure-webapp-maven-plugin:jar:1.12.0 -> com.microsoft.azure:azure-maven-plugin-lib:jar:1.4.0 -> com.microsoft.azure:azure-tools-common:jar:0.9.0 -> com.google.errorprone:error_prone_core:jar:2.4.0 -> com.google.errorprone:error_prone_check_api:jar:2.4.0 -> com.google.errorprone:javac:jar:9+181-r4173-1: 
Failed to read artifact descriptor for com.google.errorprone:javac:jar:9+181-r4173-1: Could not transfer artifact com.google.errorprone:javac:pom:9+181-r4173-1 from/to aliyunmaven (https://maven.aliyun.com/repository/public): 
Access denied to: https://maven.aliyun.com/repository/public/com/google/errorprone/javac/9+181-r4173-1/javac-9+181-r4173-1.pom -> [Help 1]

resolvent:

reach   https://mvnrepository.com/   Find javac-9 + 181-r4173-1 in and download it   Error Prone Javac

Download in files   Javac-9 + 181-r4173-1.jar to local// Attempted to add dependency in pom.xml, invalid.

Then, execute the following command in CMD:

mvn install:install-file -DgroupId=com.google.errorprone -DartifactId=javac -Dversion=9+181-r4173-1 -Dpackaging=jar -Dfile=C:\Users\Administrator\Downloads\javac-9+181-r4173-1.jar

It can be installed normally.

reference:

https://www.freesion.com/article/74941283048/

Cannot resolve plugin org.springframework .boot:xxx

   During development, sometimes when you open a project to install a dependency, or create a new springboot project to install some dependencies, the following errors appear inexplicably:

First check whether there is a problem with the network. If the network is normal, 99% of the problems occur in the Maven configuration of the idea. Open it   settings   -& gt; Find the location of the screenshot below and modify the following two places:

Maven home path: the installation directory of Maven
user setttings file:   Maven installation directory – & gt; conf -> Setting.xml file path
local repository: This is a customized Maven local repository after downloading Maven. Mine is in the Maven installation directory.

   After these three settings are completed, click apply, OK and refresh.

 

[Solved] Rabbitmq injection failed, bean creation failed, error creating bean with name ‘rabbitconnectionfactory’‘

Error creating bean with name ‘spring.rabbitmq-org.springframework.boot.autoconfigure.amqp.RabbitProperties’

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rabbitConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration$RabbitConnectionFactoryCreator.class]: Unsatisfied dependency expressed through method 'rabbitConnectionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.rabbitmq-org.springframework.boot.autoconfigure.amqp.RabbitProperties': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.autoconfigure.amqp.RabbitProperties] from ClassLoader [[email protected]]
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1179)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:923)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:326)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300)
	at com.ata.sms.simulator.Application.main(Application.java:14)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.rabbitmq-org.springframework.boot.autoconfigure.amqp.RabbitProperties': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.autoconfigure.amqp.RabbitProperties] from ClassLoader [[email protected]]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:289)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1286)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1203)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
	... 20 common frames omitted
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.autoconfigure.amqp.RabbitProperties] from ClassLoader [[email protected]]
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481)
	at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:267)
	... 33 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/amqp/rabbit/connection/AbstractConnectionFactory$AddressShuffleMode
	at java.lang.Class.getDeclaredMethods0(Native Method)
	at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
	at java.lang.Class.getDeclaredMethods(Class.java:1975)
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463)
	... 35 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.amqp.rabbit.connection.AbstractConnectionFactory$AddressShuffleMode
	at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 39 common frames omitted

Error reason: spring boot is used, but MQ. In spring boot is not used

Original dependence

<dependency>
    <groupId>org.springframework.amqp</groupId>
    <artifactId>spring-rabbit</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

Amend to read

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

Mybatis plus configuration console prints complete SQL statement with parameters

Solution
if it is application.yml

#mybatis-plus configures the console to print full SQL statements with parameters
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

If it is application.properties, add:

#mybatis-plus configures the console to print full SQL statements with parameters
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

[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”);
...

[Solved] Java.util.linkedhashmap cannot be cast to entity class

Solve the problem of java.util.linkedhashmap cannot be cast to entity class

Background description

When learning about grain mall, openfeign is used for remote call, because an interface returns R < List<· Object>> Type of data, using list <Object> When receiving data, the java.util.linkedhashmap cannot be cast to XXX data conversion exception error occurs. It can be seen that the remote call will convert the data to be converted to LinkedHashMap, but it will not work to convert it to the desired data type.

Solution one

Use typereference in fastjson tool provided by Alibaba to transform.

We add SetData () and GetData () methods to R. when getting data, we use typereference class to indicate the data type. Then convert the map to the JSON string, and then convert the JSON string to the data type we want.

public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	public R setData(Object data){
		put("data",data);
		return this;
	}

	//Reversal with fastjson
	public <T> T getData(TypeReference<T> typeReference){
		Object data = get("data");//Default is map type
		if(Objects.isNull(data)){
			return null;
		}
		String s = JSON.toJSONString(data);
		T t = JSON.parseObject("",typeReference);
		return t;
	}

Caller

        R r = wareFeignService.getSkusHasStock(skuIdList);//Remote calls
        TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
        };// Declare the internal class, specifying the type
        List<SkuHasStockVo> data = r.getData(typeReference);//get data for remote calls

reflection

This problem also occurred when using resttemplate remote call before. This problem was solved before, and the solution steps were not recorded. This time, the solution steps will be recorded to prevent the next step.

Supplementary solution 2

Recently, when reviewing the previous project code, I found a similar problem when using resttemplate remote call mentioned in my thinking. The solution at the time was this.

	import com.alibaba.fastjson.JSON;
	import com.alibaba.fastjson.JSONObject;
	
	//remote call, return the specified collection, but this collection can not be used directly, because he is a LinkedHashMap.
	List<InnerControl> remoteList = restTemplate.getForObject("url", List.class);
	remoteList = transToList(remoteList);// After the conversion, you will be able to use this collection normally.
	
	// Define a method to convert the LinkedHashMap type to the data type we want
	private List<InnerControl> transToList(List<InnerControl> list){
		String jsonStr = JSON.toJSONString(list);//still use the json conversion tool provided by alibaba.
		return JSONObject.parseArray(jsonStr, InnerControl.class);
	}

Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communicat

Solution: when connecting to the database, change usessl = true to usessl = false. Of course, if usessl = true is not written, it is true by default.

Note: however, I don’t know why I did it. What’s more, the tutorial I read only uses true, and why I report an error. If a boss sees it, he hopes to answer it.