@Mizuro0

HTTP Status 500 Spring Thymeleaf, в чем причина ошибки?

HTTP Status 500 – Внутренняя ошибка сервера

Type Exception Report

Message Servlet.init() для сервлета [dispatcher] выбросил исключение

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

jakarta.servlet.ServletException: Servlet.init() для сервлета [dispatcher] выбросил исключение
	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
	org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:673)
	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
	org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
	org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
	org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
	org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
	org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
	org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
	org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
	org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	java.base/java.lang.Thread.run(Thread.java:1589)
Root Cause

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcViewResolver' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Failed to instantiate [org.springframework.web.servlet.ViewResolver]: Factory method 'mvcViewResolver' threw exception with message: @Bean method SpringConfig.templateEngine called as bean reference for type [org.thymeleaf.spring6.SpringTemplateEngine] but overridden by non-compatible bean instance of type [org.thymeleaf.spring5.SpringTemplateEngine]. Overriding bean of same name declared in: ServletContext resource [/WEB-INF/applicationContextMVC.xml]

65b7d1be76da2392985830.png
Root Cause

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.ViewResolver]: Factory method 'mvcViewResolver' threw exception with message: @Bean method SpringConfig.templateEngine called as bean reference for type [org.thymeleaf.spring6.SpringTemplateEngine] but overridden by non-compatible bean instance of type [org.thymeleaf.spring5.SpringTemplateEngine]. Overriding bean of same name declared in: ServletContext resource [/WEB-INF/applicationContextMVC.xml]

65b7d2101e481424048578.png
Root Cause

java.lang.IllegalStateException: @Bean method SpringConfig.templateEngine called as bean reference for type [org.thymeleaf.spring6.SpringTemplateEngine] but overridden by non-compatible bean instance of type [org.thymeleaf.spring5.SpringTemplateEngine]. Overriding bean of same name declared in: ServletContext resource [/WEB-INF/applicationContextMVC.xml]
Apache Tomcat/10.1.18

65b7d240b87ab362045882.png
Конфигурационный файл
package org.mizuro.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

@Configuration
@ComponentScan("org.mizuro.spring")
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
    private final ApplicationContext applicationContext;

    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }
}


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.mizuro.spring</groupId>
    <artifactId>SpringMVC</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringMVC Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>6.1.3</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0-M1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring6</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.10.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>jakarta.servlet.jsp.jstl</groupId>
            <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
            <version>3.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringMVC</finalName>
    </build>
</project>


Класс контроллер
package org.mizuro.spring.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/first")
public class FirstController {

    @GetMapping("/hello")
    public String helloPage() {

        return "first/hello";
    }

    @GetMapping("/goodbye")
    public String goodbyePage() {
        return "first/goodbye";
    }
}


Диспетчер Сервелатов
package org.mizuro.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}


Использую томкат 10.1.18, пробовал запустить на томкат 9.0.85 но там уже ошибка с видимостью ресурсов.
Не могу осмыслить в чем проблема, как мне кажется с версией зависимостей
https://github.com/Mizuro0/SpringApplication
Вот ссылка на репозиторий проекта
Все перепробовал
Извиняюсь за такой формат представления ошибки в виде скриншотов
  • Вопрос задан
  • 287 просмотров
Пригласить эксперта
Ответы на вопрос 2
leahch
@leahch
3D специалист. Dолго, Dорого, Dерьмово.
Переместите вашу папочку /src/main/webapp/WEB-INF/views в /src/main/resources/views (лучше сюда) или /src/main/webapp/views

PS. Ох, боже, какое это все старье...
Springboot возьмите хотя бы, или javalin, или sparkjava уже предлагал...)

ЗЫЫ.
import io.javalin.Javalin;

public class HelloWorld {
    public static void main(String[] args) {
        Javalin app = Javalin.create().start(7000);
        app.get("/", ctx -> ctx.result("Hello World"));
    }
}
Ответ написан
@My1Name
В классе SpringConfig:
@Bean
public SpringResourceTemplateResolver templateResolver(){
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(servletContext);
    templateResolver.setPrefix("/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setCacheable(false); // отключаем везде кэш на время разработки 
    return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.setEnableSpringELCompiler(true);
    return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver(){
	ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
	viewResolver.setTemplateEngine(templateEngine());
	viewResolver.setCharacterEncoding("UTF-8");
	return viewResolver;
}

Вместо jakarta.servlet и thymeleaf-spring6 в poom.xml
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<scope>provided</scope>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>

Класс MySpringMvcDispatcherServletInitializer можно (и нужно) удалить.

Под Spring6 - Spring Security (если я не ошибаюсь) - ещё не работает.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы