Tag Archives: spring

JDK upgrade 17 project reports an error java.lang.reflect.inaccessibleobjectexception

When upgrading java11 to java17, the project starts normally, and an error is reported when executing the mybatis query

According to the error message, it is suspected that there is a problem with mybatis XML configuration. It is found that there is no problem. Jdk11 starts normally

reating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3c88e19e] was not registered for synchronization because synchronization is not active
JDBC Connection [org.apache.shardingsphere.shardingjdbc.jdbc.core.connection.ShardingConnection@5b6098ff] will not be managed by Spring
==>  Preparing: select id, user_id as userId, order_id as orderId, remark, create_time as createTime from t_order where order_id=?
==> Parameters: 12(Long)
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3c88e19e]
2021-09-20 22:47:33.431 ERROR 19452 --- [nio-9090-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.reflect.InaccessibleObjectException: Unable to make field private static final long java.lang.Number.serialVersionUID accessible: module java.base does not "opens java.lang" to unnamed module @708f5957
### The error may exist in file [D:\java\IdeaProjects\sharding-demo\target\classes\mapper\OrderMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: select             id,             user_id as userId,             order_id as orderId,             remark,             create_time as createTime         from t_order         where order_id=?
### Cause: java.lang.reflect.InaccessibleObjectException: Unable to make field private static final long java.lang.Number.serialVersionUID accessible: module java.base does not "opens java.lang" to unnamed module @708f5957] with root cause

java.lang.reflect.InaccessibleObjectException: Unable to make field private static final long java.lang.Number.serialVersionUID accessible: module java.base does not "opens java.lang" to unnamed module @708f5957
	at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354) ~[na:na]
	at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297) ~[na:na]
	at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178) ~[na:na]
	at java.base/java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:130) ~[na:na]
	at org.codehaus.groovy.reflection.CachedClass$1$1.run(CachedClass.java:55) ~[groovy-2.4.5-indy.jar:2.4.5]
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:318) ~[na:na]
	at org.codehaus.groovy.reflection.CachedClass$1.initValue(CachedClass.java:50) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.reflection.CachedClass$1.initValue(CachedClass.java:48) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:49) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:36) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.reflection.CachedClass.getFields(CachedClass.java:264) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaClassImpl.addFields(MetaClassImpl.java:2377) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaClassImpl.inheritFields(MetaClassImpl.java:2372) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaClassImpl.setupProperties(MetaClassImpl.java:2259) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaClassImpl.addProperties(MetaClassImpl.java:3302) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaClassImpl.initialize(MetaClassImpl.java:3266) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(ClassInfo.java:254) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:285) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:295) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.getMetaClass(MetaClassRegistryImpl.java:261) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.InvokerHelper.getMetaClass(InvokerHelper.java:873) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.callsite.CallSiteArray.createPojoSite(CallSiteArray.java:125) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:166) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) ~[groovy-2.4.5-indy.jar:2.4.5]
	at Script6$_run_closure1.doCall(Script6.groovy:1) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
	at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1019) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.Closure.call(Closure.java:426) ~[groovy-2.4.5-indy.jar:2.4.5]
	at groovy.lang.Closure.call(Closure.java:420) ~[groovy-2.4.5-indy.jar:2.4.5]
	at org.apache.shardingsphere.core.strategy.route.inline.InlineShardingStrategy.execute(InlineShardingStrategy.java:94) ~[sharding-core-common-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.core.strategy.route.inline.InlineShardingStrategy.doSharding(InlineShardingStrategy.java:76) ~[sharding-core-common-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.core.strategy.route.inline.InlineShardingStrategy.doSharding(InlineShardingStrategy.java:63) ~[sharding-core-common-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRoutingEngine.routeTables(ShardingStandardRoutingEngine.java:214) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRoutingEngine.route0(ShardingStandardRoutingEngine.java:195) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRoutingEngine.routeByShardingConditionsWithCondition(ShardingStandardRoutingEngine.java:121) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRoutingEngine.routeByShardingConditions(ShardingStandardRoutingEngine.java:115) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRoutingEngine.getDataNodes(ShardingStandardRoutingEngine.java:96) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRoutingEngine.route(ShardingStandardRoutingEngine.java:74) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.ShardingRouteDecorator.decorate(ShardingRouteDecorator.java:69) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.sharding.route.engine.ShardingRouteDecorator.decorate(ShardingRouteDecorator.java:53) ~[sharding-core-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.underlying.route.DataNodeRouter.executeRoute(DataNodeRouter.java:91) ~[shardingsphere-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.underlying.route.DataNodeRouter.route(DataNodeRouter.java:76) ~[shardingsphere-route-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.underlying.pluggble.prepare.PreparedQueryPrepareEngine.route(PreparedQueryPrepareEngine.java:54) ~[shardingsphere-pluggable-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.underlying.pluggble.prepare.BasePrepareEngine.executeRoute(BasePrepareEngine.java:96) ~[shardingsphere-pluggable-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.underlying.pluggble.prepare.BasePrepareEngine.prepare(BasePrepareEngine.java:83) ~[shardingsphere-pluggable-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.prepare(ShardingPreparedStatement.java:183) ~[sharding-jdbc-core-4.1.1.jar:4.1.1]
	at org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.execute(ShardingPreparedStatement.java:143) ~[sharding-jdbc-core-4.1.1.jar:4.1.1]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
	at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59) ~[mybatis-3.5.7.jar:3.5.7]
	at jdk.proxy3/jdk.proxy3.$Proxy95.execute(Unknown Source) ~[na:na]
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:64) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:325) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:89) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:151) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:145) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140) ~[mybatis-3.5.7.jar:3.5.7]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:427) ~[mybatis-spring-2.0.6.jar:2.0.6]
	at jdk.proxy2/jdk.proxy2.$Proxy65.selectList(Unknown Source) ~[na:na]
	at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:224) ~[mybatis-spring-2.0.6.jar:2.0.6]
	at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:147) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:80) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:145) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:86) ~[mybatis-3.5.7.jar:3.5.7]
	at jdk.proxy2/jdk.proxy2.$Proxy66.getOrderByOrderId(Unknown Source) ~[na:na]
	at com.fancv.shardingdemo.service.impl.OrderServiceImpl.getOrderByOrderId(OrderServiceImpl.java:26) ~[classes/:na]
	at com.fancv.shardingdemo.controller.OrderController.getOrderInfo(OrderController.java:42) ~[classes/:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]

Search data discovery

Someone is experiencing the same problem when upgrading to jdk9

By adding startup parameters

--add-opens java.base/java.lang=ALL-UNNAMED

Original information

The following error message appears:

Exception in thread “main”
java.lang.reflect.InaccessibleObjectException: Unable to make field
private static final long java.lang.Long.serialVersionUID accessible:
module java.base does not “opens java.lang” to unnamed module
@224aed64
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible (AccessibleObject.java:207)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:171)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:165)
at com.jdojo.intruder.TestManifestAttributes.main(TestManifestAttributes.java:10)
A runtime error indicates that the application cannot access the private static serialVersionUID because the java.lang package in the java.base module is not open. Let’s try the – add opens option first:

C: \ java9revealed & gt; Java — add opens Java. Base/Java. Lang = all unnamed
– jar com.jdojo.intruder \ dist \ com.jdojo.intruder.jar output information is as follows:

Long. SerialVersionUID = 4290774380558885855 this command works normally and verify that the command line option is the solution in this case.
we use the add opens attribute in the manifest.mf file to fix this error, as shown below.

Manifest version: 1.0 main class:
com.jdojo.intruder.testmanifestattributes add opens:
java.base/java.lang recreate the executable jar and run it with the same command:

C: \ java9revealed & gt; Java – jar
com.jdojo.intruder \ dist \ com.jdojo.intruder.jar the output result is:

Long.serialVersionUID=4290774380558885855

Run the project again and query the data successfully

Summary: upgrading from java11 to java17 is a personal computer at home, not a production environment,

It takes about 5 hours to solve the problem, because the project is a shared research project, involving many knowledge points, and it takes a long time to locate the problem.

Difficult: the project itself has no problem starting jdk11, but an error is reported after upgrading jdk15.

reference material: https://www.cnblogs.com/IcanFixIt/p/7144366.html

Technical exchange group:

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

framework: springboot+IDEA+spring security oauth2
background: user login to get token, username or password authentication failure, the execution of onAuthenticationFailure method, has returned the normal error code and error message, but the console still throws an exception, the error message is as follows.

2021-09-12 07:16:25.490  WARN 964 — [nio-8090-exec-1] d.c.h.CustomAuthenticationFailureHandler : Authentication failed, the return message is: {“code”:1100, “info”: “User does not exist.”}
2021-09-12 07:16:25.500 ERROR 964 — [nio-8090-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/api/sso] threw exceptionjava.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:456) ~[tomcat-embed-core-9.0.52.jar:9.0.52]
at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120) ~[tomcat-embed-core-9.0.52.jar:4.0.FR]
at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120) ~[tomcat-embed-core-9.0.52.jar:4.0.FR]
at org.springframework.security.web.util.OnCommittedResponseWrapper.sendError(OnCommittedResponseWrapper.java:126) ~[spring-security-web-5.5.2.jar:5.5.2]
at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.onAuthenticationFailure(SimpleUrlAuthenticationFailureHandler.java:86) ~[spring-security-web-5.5.2.jar:5.5.2]
at com.datong.liran.datongssoserver.config.handle.CustomAuthenticationFailureHandler.onAuthenticationFailure(CustomAuthenticationFailureHandler.java:39) ~[classes/:na]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.unsuccessfulAuthentication(AbstractAuthenticationProcessingFilter.java:342) ~[spring-security-web-5.5.2.jar:5.5.2]

The error code and error message have been returned normally, but the console still reports an error, not the result I want, so what should I do? The custom exception handling code looks like this.

@Component("CustomAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.reset();
//        PrintWriter printWriter = httpServletResponse.getWriter();
        OutputStream out = response.getOutputStream();
        response.setContentType("application/json;charset=UTF-8");
        Result result = Result.error(1100,exception.getMessage(),null);
        String rspBodyStr = JSONObject.toJSONString(result);
        logger.warn("The authentication fails and the return message is:"+rspBodyStr);
        out.write(rspBodyStr.getBytes(StandardCharsets.UTF_8));
        out.close();
        super.onAuthenticationFailure(request,response,exception);
    }
}

Cannot call senderror() after the response has been committed.

Analysis: according to the error log, it is preliminarily judged that it should be repeated submission or repeated return, but only response is involved here, so you can only go to the parent class (onauthenticationfailure). Open it and have a look. The code is as follows.

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (this.defaultFailureUrl == null) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Sending 401 Unauthorized error since no failure URL is set");
            } else {
                this.logger.debug("Sending 401 Unauthorized error");
            }

            response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        } else {
            this.saveException(request, exception);
            if (this.forwardToDestination) {
                this.logger.debug("Forwarding to " + this.defaultFailureUrl);
                request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
            } else {
                this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl);
            }

        }
    }

Obviously, when the defaultfailureurl is null, the senderror () method is executed, which should be the same as the previous setting, and this method also reports an error in the error log. Since the error code and error information I want have been returned, I simply do not call the parent method. After a try, sure enough, the console no longer reports an error and returns normally.

Solution: no longer call the parent class method, and annotate super.onauthenticationfailure (request, response, exception); sentence.

OK, get it done and start sharing the joy of success.

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [XXX]

Error record:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [currentUserCartItems]

Background: Spring + thymeleaf reports an error

Reason: no @ respontroller or @ ResponseBody annotation is written on the method of data returned by the controller, and the returned data will be converted to JSON format

note: if it is necessary to return page Jump, it is best to add @ ResponseBody annotation on the specific method of data returned, otherwise other controllers cannot jump to the page normally

When idea generates a spring boot project, error: read timed out appears

When using idea to generate spring boot projects, the following occurs: error: read timed out ,

The solution is as follows:

    click file in the upper right corner of idea and select settings in the list. Click settings
    to open the settings box, and select appearance & amp; on the left; Behavior –> System Settings –> HTTP proxy, select auto detect proxy settings on the right, click Check connection below, and fill in in the pop-up box https://start.spring.io , click OK
    , and the connection successful information will be displayed in the pop-up box, and it will succeed.

spring cloud 2020 gateway Error 503 [How to Solve]

POM file dependency

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--gateway fhadmin.org-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
        <version>3.0.2</version>
    </dependency>
    <!--spring-boot fhadmin.org-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

The related dependencies of Nacos I added in the parent component are as follows:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>${nacos.version}</version>
</dependency>
<!--alibaba fhadmin.org-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>${nacos.version}</version>
</dependency>

The version of Nacos is as follows:

<properties>
    <nacos.version>2021.1</nacos.version>
</properties>

The application.yml file of gateway is configured as follows:

#fhadmin.org
server:
  port: 9040

spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes:
        - id: consumer
          uri: lb://consumer
          #          uri: http://localhost:9010
          predicates:
            - Path=/**
    nacos:
      discovery:
        server-addr: localhost:8848
        metadata:
          preserved.heart.beat.interval: 3 
          preserved.heart.beat.timeout: 6 
          preserved.ip.delete.timeout: 9 

When I pass URI: http://localhost:9010 When calling a service, it can be called, but when I use URI LB:// consumer, I cannot call the service, and an error 503 is reported

The solution is:
Add feign dependency.

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

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
        <version>3.0.2</version>
    </dependency>

    <!--fegin fhadmin.cn-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>3.0.2</version>
    </dependency>
    <!-- Feign Client for loadBalancing -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-loadbalancer</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Guess the reason: Nacos is compatible with feign. Feign integrates ribbon and realizes load balancing by default; Maybe Nacos is not compatible with the ribbon of springcloud gateway.

springboot sqlserver druid reward: validateConnection false

The exception information is as follows:

java.sql.SQLException: validateConnection false
	at com.alibaba.druid.pool.DruidAbstractDataSource.validateConnection(DruidAbstractDataSource.java:1418)
	at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnection(DruidAbstractDataSource.java:1733)
	at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(DruidDataSource.java:2801)
Caused by: java.lang.NullPointerException: null
	at com.alibaba.druid.wall.WallProvider.checkInternal(WallProvider.java:707)
	at com.alibaba.druid.wall.WallProvider.check(WallProvider.java:584)
	at com.alibaba.druid.wall.WallFilter.checkInternal(WallFilter.java:826)
	at com.alibaba.druid.wall.WallFilter.check(WallFilter.java:821)
	at com.alibaba.druid.wall.WallFilter.statement_execute(WallFilter.java:454)
	at com.alibaba.druid.filter.FilterChainImpl.statement_execute(FilterChainImpl.java:3008)
	at com.alibaba.druid.filter.FilterAdapter.statement_execute(FilterAdapter.java:2484)
	at com.alibaba.druid.filter.FilterEventAdapter.statement_execute(FilterEventAdapter.java:188)
	at com.alibaba.druid.filter.FilterChainImpl.statement_execute(FilterChainImpl.java:3008)
	at com.alibaba.druid.proxy.jdbc.StatementProxyImpl.execute(StatementProxyImpl.java:147)
	at com.alibaba.druid.pool.vendor.MSSQLValidConnectionChecker.isValidConnection(MSSQLValidConnectionChecker.java:50)
	at com.alibaba.druid.pool.DruidAbstractDataSource.validateConnection(DruidAbstractDataSource.java:1398)

Follow this method: com.alibaba.druid.pool.druidabstractdatasource.validateconnection

result = validConnectionChecker.isValidConnection(conn, validationQuery, validationQueryTimeout);

Find the exception of this line of code and enter this method

Find the method of this implementation class (because it is SQL server)

public boolean isValidConnection(final Connection c, String validateQuery, int validationQueryTimeout) throws Exception {
        if (c.isClosed()) {
            return false;
        }

        Statement stmt = null;

        try {
            stmt = c.createStatement();
            if (validationQueryTimeout > 0) {
                stmt.setQueryTimeout(validationQueryTimeout);
            }
            stmt.execute(validateQuery);
            return true;
        } catch (SQLException e) {
            throw e;
        } finally {
            JdbcUtils.close(stmt);
        }
    }

Finally, it is found that the method parameter validatequery is null, so a null pointer is reported. Let’s go back and see why it is null

protected volatile String                          validationQuery                           = DEFAULT_VALIDATION_QUERY;

Class defines that validationquery is equal to default_ VALIDATION_ Query, and default_ VALIDATION_ Query initialization is defined as null. In fact, this parameter comes from the springboot configuration file

Add the following configuration in the springboot data source configuration file:

druid:
                        validation-query: SELECT 1

Just do it!

PS, data source configuration:

driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://IP:PORT;DatabaseName=database name
username: username
password: password
druid:
    validation-query: SELECT 1

[Solved] XxlJob Error: XxlJobFileAppender [101] -| Permission denied

1. Xxljob reports an error. Xxljobfileappender [101] – [permission denied

An error is reported in xxljob: xxljobfileappender [101] – [permission denied. The detailed error is as follows:

2021-09-15 09:28:45.686 |-ERROR [Thread-1565] com.xxl.job.core.log.XxlJobFileAppender [101] -| Permission denied
java.io.IOException: Permission denied
        at java.io.UnixFileSystem.createFileExclusively(Native Method)
        at java.io.File.createNewFile(File.java:1012)
        at com.xxl.job.core.log.XxlJobFileAppender.appendLog(XxlJobFileAppender.java:99)
        at com.xxl.job.core.context.XxlJobHelper.logDetail(XxlJobHelper.java:164)
        at com.xxl.job.core.context.XxlJobHelper.log(XxlJobHelper.java:118)
        at com.cuai.cbam.monitor.task.SystemOperateTask.checkSystemTask(SystemOperateTask.java:41)
        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:498)
        at com.xxl.job.core.handler.impl.MethodJobHandler.execute(MethodJobHandler.java:31)
        at com.xxl.job.core.thread.JobThread.run(JobThread.java:163)

2. Positioning problem

After analyzing the log, you can find that it is normal to use logback to output the log, but use * * xxljobhelper.log (“…”)** When an error is reported, check the relevant configuration of xxljob and find a logpath parameter. Combined with the error, it is speculated that the server does not have the configured logpath path or the current operating user does not have the operation permission of the logpath path

3. Problem solving

Grant the logpath path the permission that the current user can operate, and then restart the application. It is found that the program is normal. So far, the problem has been solved.

Solution to error reporting on the client caused by adding fields on the CXF server

To solve this problem, turn off the field verification function

1. Spring framework:

Add the following configuration in the configuration file

<cxf:properties>
   <entry key="set-jaxb-validation-event-handler" value="false"/>
</cxf:properties>

2. Springboot framework:

Add @ endpointproperties annotation on WebService implementation class

@WebService(
        targetNamespace = "http://ws.test.com/",
        serviceName = "demoWebService",
        endpointInterface = "com.test.ws.DemoWebService")
@EndpointProperties({@EndpointProperty(key = "set-jaxb-validation-event-handler", value ="false")})
@Configuration
public class FaultOrderWebServiceImpl implements DemoWebService {

}

Mac idea springboot project reported an error

Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_ 144.jdk/Contents/Home/bin/java (0x10dd324c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_ 144.jdk/contents/home/jre/lib/libinstrument.dylib error

To solve the problem, you need to set the idea custom properties. Click Help on the navigation bar and select Edit custom properties,

For the first time, there is no properties file. At this time, the following interface will pop up in idea to prompt you to create it. Click Create directly.

Write idea. No. launcher = true in idea.properties, and then restart idea.

[Maven] maven filtering OTS parsing error incorrect file size in WOFF head [Two Methods to Solve]

Background description

The front-end static resource file is placed in the Resources folder of the back-end spring boot project. After multi-environment packaging, the icon and text on the front-end page are not displayed as expected. Check the browser console and find the following errors.

OTS parsing error: incorrect file size in WOFF header

Cause location

Let’s first look at the configured Maven POM content.

<build>
        <finalName>project-name</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>utf-8</encoding>
                    <delimiters>
                        <delimiter>@</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>

You can see that the filtering tag is true, which indicates that the filtering mode is enabled. So what is the function of filtering true?

Filtering: turn on filtering and replace the parameter (eg. ${name}) in the file under the directory with the specified parameter. Directory: specify the location of the resource file.

However, it should be noted that because the project needs to configure multiple environments, it needs to use @profile. Active @ , so the @ method is configured for replacement instead of using the default $symbol.

# application.ymlIn the file
spring:
  # Configure which environment to use, dev development, beta testing, prod online, mainly different data sources.
  profiles:
    # Get the environment specified by maven
    active: @profile.active@

Therefore, the main meaning of the above POM is to replace all @ XXX @ under Src/main/resources. Please refer to the relevant contents of Maven profile for the specific replacement principle, which will not be introduced here.

Solution:

Because there are many @ symbols in the woff file, the above configuration causes the original content of the woff file to be replaced, which leads to errors in browser parsing
therefore, the core of the solution is to prevent woff files from being scanned under filtering.

Scheme 1: when the filtering mode is started, the contents in the static directory will not be replaced.

    <build>
        <finalName>package-name</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>utf-8</encoding>
                    <delimiters>
                        <delimiter>@</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!-- Turn on filtering and replace the parameters in the file under directory with the specified parameters -->
                <filtering>true</filtering>
                <! -- Use filter to exclude files under fonts/ first, otherwise the page icon will not be loaded -->
                <excludes>
                    <exclude>static/fonts/**</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <!-- Re-copy the excluded files under fonts/ without using the filter -->
                <filtering>false</filtering>
                <includes>
                    <include>static/fonts/**</include>
                </includes>
            </resource>
        </resources>
    </build>

Scheme 2: the nonfilteredfileextensions tag specifies which suffix files are not uniformly encoded.

    <build>
        <finalName>package-name</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>utf-8</encoding>
                    <delimiters>
                        <delimiter>@</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                    <nonFilteredFileExtensions>woff</nonFilteredFileExtensions>
                    <nonFilteredFileExtensions>woff2</nonFilteredFileExtensions>
                    <nonFilteredFileExtensions>tff</nonFilteredFileExtensions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration…

ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property ‘log4j2.debug’ to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2

This text probably means that there is no Log4j 2 configuration file
Create a new Log4j 2.xml file and paste the code of this text in the file, then run the file and it’s OK

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
        </Console>

        <RollingFile name="RollingFile" filename="log/test.log"
                     filepattern="${logPath}/%d{YYYYMMddHHmmss}-fargo.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="10 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console" />
            <AppenderRef ref="RollingFile" />
        </Root>
    </Loggers>
</Configuration>

[Solved] Error creating bean with name ‘org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0‘:

Error:
Error creating bean with name’org.springframework.web.servlet.handler.SimpleUrlHandlerMapping0’: Instantiation of bean failed;


Error Message:

05-Sep-2021 16:44:18.866 Message [http-apr-8080-exec-8] 
org.springframework.web.servlet.FrameworkServlet.initServletBean Initializing Servlet 'springmvc'

05-Sep-2021 16:44:18.974 Warning [http-apr-8080-exec-8] org.springframework.context.support.AbstractApplicationContext.refresh Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.core.log.LogDelegateFactory.getHiddenLog(Ljava/lang/String;)Lorg/apache/commons/logging/Log;

Cause analysis:

bean instantiation failed


Solution:

There are three ways:

1. Comment out the following comments.

2.Servlet API dependency is missing. Add the following dependencies

 <dependency>
      <groupId>tomcat</groupId>
      <artifactId>servlet-api</artifactId>
      <version>5.5.23</version>
    </dependency>

3.the web project created has the wrong prototype selected