【问题标题】:Unable to run Spring Boot WebMVC with Thymeleaf support无法在 Thymeleaf 支持下运行 Spring Boot WebMVC
【发布时间】:2016-09-09 07:24:18
【问题描述】:

我搜索了很多,但我没有找到我的问题的答案,所以我在这里发布我的问题。请查看并建议我错误的解决方案。

我使用 Spring Tool Suite(STS) 创建了支持 thymeleaf 的 spring boot web mvc 项目。当我运行它时,给我“Whitelabel Error Page”页面。这意味着未找到映射。

努力:

WebConfig.java

package com.springthymeleaf.config;

import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

@Configuration
@ComponentScan("com.springthymeleaf")
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter  {

    @Bean
    ServletRegistrationBean servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean();
        registrationBean.addUrlMappings("/console/*");
        return registrationBean;
    }

    //start Thymeleaf specific configuration
    @Bean(name ="templateResolver") 
    public ServletContextTemplateResolver getTemplateResolver() {
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
//      templateResolver.setPrefix("/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("XHTML");
    return templateResolver;
    }
    @Bean(name ="templateEngine")       
    public SpringTemplateEngine getTemplateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(getTemplateResolver());
    return templateEngine;
    }
    @Bean(name="viewResolver")
    public ThymeleafViewResolver getViewResolver(){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); 
        viewResolver.setTemplateEngine(getTemplateEngine());
    return viewResolver;
    }
    //end Thymeleaf specific configuration
    @Bean(name ="messageSource")
    public MessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/i18/thymeleafResource");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}

SecurityConfiguration.java

package com.springthymeleaf.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
    }
}

ServletInitializer.java

package com.springthymeleaf;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringThymeLeafApplication.class);
    }

}

SpringThymeLeafApplication.java

package com.springthymeleaf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringThymeLeafApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringThymeLeafApplication.class, args);
    }
}

IndexController.java

package com.springthymeleaf.controllers;


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

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(){
        return "index";
    }
}

我在资源/模板文件夹中创建了index.html 文件。我仍然收到那个错误。我在网上搜索了很多,但没有得到任何线索。请有人帮助我。

【问题讨论】:

  • 删除您的 Web 配置类。 Spring Boot 已经为您配置好了。对于 I18N 支持,请将 spring.messages.basename=/WEB-INF/i18/thymeleafResource 添加到您的 application.properties。简而言之,使用框架而不是围绕框架工作。
  • 我已经删除了 WebConfig.java 文件,现在我也不想使用任何资源,所以我还没有配置资源包。在此之后我尝试运行我仍然遇到同样的问题。
  • 添加您的目录结构。此外,错误页面可能意味着完全不同的东西,请检查您的日志是否有错误(并将该堆栈跟踪/错误添加到您的问题中)。
  • 我已经用目录结构截图更新了我的问题。请查看并建议我解决方案。
  • 我还在模板文件夹中添加了 error.html 页面。现在,每当我尝试访问任何页面时,它只会向我显示 error.html 页面,而不是实际的页面表单 indexcontroller,它是用于“/”映射的模板文件夹中的 index.html。

标签: java spring spring-mvc thymeleaf


【解决方案1】:

实际上 Spring Boot 开箱即用地配置了 Thymeleaf。它应该适用于以下设置:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll() // http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-form
                .and()
            .logout().permitAll(); // http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-logout
    }

    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web
            .ignoring()
                .antMatchers("/resources/**"/*, ... */);
    }
}

@Controller
public class LoginController
{
    @RequestMapping("/login")
    static String login(Model model)
    {
        return "login";
    }
}

【讨论】:

  • 不是它不工作。它带我进入没有上下文根路径的登录页面。
  • @Mandy 我在 LoginController Annotation 中犯了一个错误。将“/”更改为“/login”...“没有上下文根路径”是什么意思?上面的设置应该保护任何请求,并且应该重定向到“/login”下的登录页面。成功登录后,它应该重定向到“/”。
  • 这里我们需要更多的东西来让我做实际的项目来工作。我还要感谢 M. Deinum 没有他的指导,我将无法完成我的任务。谢谢 Deinum。
【解决方案2】:

Spring Boot 已经为您配置了 Thymeleaf,因此无需手动配置。删除所有 Thymeleaf 相关配置,同时删除 @EnableWebMvc,因为这会干扰 Spring Boot 自动配置。 @ComponentScan 也是多余的。

Spring Boot 还为您注册了一个 MessageSource,因此无需对其进行配置。不确定 servlet 注册是做什么的,但这是您唯一需要的。

我还建议删除您的控制器并使用您可以在 WebConfig 类中配置的视图控制器。为您节省一个控制器。

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter  {

    @Bean
    ServletRegistrationBean servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean();
        registrationBean.addUrlMappings("/console/*");
        return registrationBean;
    }

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }
}

要让自动配置的消息源获取您的自定义捆绑包,请将以下内容添加到 src/main/resources/application.properties

spring.messages.basename=/WEB-INF/i18/thymeleafResource

我还建议让SpringThymeLeafApplication 扩展SpringBootServletInitializer

@SpringBootApplication
public class SpringThymeLeafApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(SpringThymeLeafApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringThymeLeafApplication.class);
    }
}

还要确保您的模板位于 src/main/resources/templates 而不是 src/main/resources/resources/templates 中,否则将找不到这些模板。

【讨论】:

  • 我已经完成了你提到的所有事情。我已经删除了 webconfig.java 之类的所有内容以及与 thymeleaf 相关的所有内容。只有安全配置和启动配置。我还在模板中创建了 error.html 页面。不是显示控制器页面的错误页面。
  • 感谢 Deinum 没有您的帮助,我不会再做进一步的了。正如你的回答和 shinchillahh 的回答让我走得更远。在这里我只能接受一个答案,但为你投票。
【解决方案3】:

当您添加 thymeleaf 依赖项时,Spring boot 会进行所有自动配置。那么您应该执行以下操作。

  1. 删除您在 WebConfig.java 上的所有 thymeleaf 配置
  2. 如果您使用 Maven,请确保您的 pom.xml 具有以下依赖项,否则如果您使用 gradle,请检查 spring 网站以获取等效项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  3. 第三,确保扫描控制器所在的位置,在 SpringThymeLeafApplication.java 中添加以下内容:

    @ComponentScan(basePackages = "your.path.to.controllers")

  4. 最后,您必须将 .html 文件添加到资源/模板中

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2018-06-20
    • 2019-02-26
    • 2019-06-11
    • 1970-01-01
    • 2015-07-29
    • 2014-11-28
    • 1970-01-01
    • 2017-07-13
    相关资源
    最近更新 更多