Search code examples
spring-bootspring-mvcthymeleaf

ThymeleafView: java.lang.IllegalArgumentException: Property 'locale' is required


I follow the below tutorial step by step to complete NO.10 Rendering Template Fragments.

https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#rendering-template-fragments

And I get an exception: nested exception is java.lang.IllegalArgumentException: Property 'locale' is required.

My code is below, Could someone tell me how to fix it? Thank you very much.

WebConfig.java

public class WebConfig implements WebMvcConfigurer {

@Autowired
private WebApplicationContext context;

@Bean
public ServletContextTemplateResolver templateResolver() {
    final ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context.getServletContext());
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode(TemplateMode.HTML);
    return resolver;
}

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

@Bean
public ThymeleafViewResolver viewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    return viewResolver;
}

@Bean("messageSource")
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasenames("lang/messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

@Bean
public LocaleResolver localeResolver() {
    return new CookieLocaleResolver();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    registry.addInterceptor(localeChangeInterceptor);
}

@Bean(name = "content-part")
@Scope("prototype")
public ThymeleafView someViewBean() {
    ThymeleafView view = new ThymeleafView("index"); // templateName = 'index'
    view.setMarkupSelector("content");
    return view;
}

}

HomeController.java

public class HomeController {
@RequestMapping("/showContentPart")
public String showContentPart(final Locale locale, HttpServletRequest request, HttpServletResponse response) {
    return "content-part";
}

}

index.html https://i.sstatic.net/WOGpR.png


Solution

  • Try this :

    @RequestMapping("/showContentPart")

    public class HomeController { public String showContentPart(final Locale locale, HttpServletRequest request, HttpServletResponse response) { return "content-part"; }