简体   繁体   English

无法运行具有Thymeleaf支持的Spring Boot WebMVC

[英]Unable to run Spring Boot WebMVC with Thymeleaf support

I have search a lot but I did not find answer to my question, So I am posting my question here. 我进行了很多搜索,但是没有找到问题的答案,因此,我在此处发布问题。 Please look and suggest me the solution where I am mistaken. 请查看并向我提出我误解的解决方案。

I have created spring boot web mvc project with thymeleaf support using Spring Tool Suite(STS). 我已经使用Spring Tool Suite(STS)创建了带有百里香支持的spring boot web mvc项目。 When I run it give me "Whitelabel Error Page" page. 当我运行它时,请给我“ Whitelabel错误页面”页面。 Which means mapping not found. 这意味着找不到映射。

Efforts: 努力:

WebConfig.java 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 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 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 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 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";
    }
}

I have created index.html file in resources/templates folder. 我已经在resources / templates文件夹中创建了index.html文件。 Still I am getting that error. 我仍然收到该错误。 I have searched a lot on web, but did not get clue. 我在网上进行了很多搜索,但没有得到任何线索。 Please somebody help me. 请有人帮我。

目录结构

Actually Spring Boot configures Thymeleaf out of the box. 实际上,Spring Boot是开箱即用地配置Thymeleaf的。 It should work with the following setup: 它应与以下设置一起使用:

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

Spring Boot already configures Thymeleaf for you, so no need to configure that manually. Spring Boot已经为您配置了Thymeleaf,因此无需手动配置。 Remove all Thymeleaf related configuration, also remove @EnableWebMvc as that interferes with the Spring Boot auto configuration. 删除所有与Thymeleaf相关的配置,同时也删除@EnableWebMvc因为这会干扰Spring Boot自动配置。 The @ComponentScan is also redundant. @ComponentScan也是多余的。

Spring Boot also registered a MessageSource for you so no need to configure that. Spring Boot还为您注册了一个MessageSource ,因此无需进行配置。 Not sure what the servlet registration is you do but that is the only thing you need. 不知道您要进行什么servlet注册,但这是您唯一需要的。

Also I suggest to remove your controller and use a view controller which you can configure in your WebConfig class. 另外,我建议删除控制器,并使用可以在WebConfig类中配置的视图控制器。 Saves you a controller. 为您节省控制器。

@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");
    }
}

To let the auto configured message source pickup your custom bundles add the following to src/main/resources/application.properties . 要让自动配置的消息源提取您的自定义捆绑包,请将以下内容添加到src/main/resources/application.properties

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

I would also suggest to simply let the SpringThymeLeafApplication extend the SpringBootServletInitializer . 我还建议简单地让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);
    }
}

Also make sure that your templates are in src/main/resources/templates and not in src/main/resources/resources/templates else those will not be found. 还要确保您的模板位于src/main/resources/templates ,而不位于src/main/resources/resources/templates否则将找不到这些src/main/resources/resources/templates

Spring boot does all the automatic configuration when you add the thymeleaf dependency. 当您添加百里香依赖时,Spring Boot会执行所有自动配置。 then you should do the following. 那么您应该执行以下操作。

  1. Remove all the thymeleaf configuration you have on your WebConfig.java 删除您在WebConfig.java上拥有的所有thymeleaf配置
  2. Make sure you have the following dependency your pom.xml if you are using Maven, otherwise check the spring website for the equivalent if you are using gradle: 如果使用的是Maven,请确保pom.xml具有以下依赖关系;如果使用的是gradle,请确保在spring网站上找到相应的依赖项:

     <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 
  3. thirdly you make sure that you scanning where your controllers are, add the following on your SpringThymeLeafApplication.java: 第三,确保您扫描了控制器的位置,在SpringThymeLeafApplication.java中添加以下内容:

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

  4. Finally you have to add your .html files to resources/templates 最后,您必须将.html文件添加到资源/模板中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM