0

When I use thymeleaf in SpringMVC,the ServletContext throw nullpointexception ,here my code and trace stack

@Configuration

public class ViewResolverConfig {

    @Bean
    public ITemplateResolver templateResolver() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
       
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }
   
    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }
    
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }}

here is the buttom error

Caused by: java.lang.NullPointerException: null at com.lh.config.WebConfig.templateResolver(WebConfig.java:46) at com.lh.config.WebConfig$$EnhancerBySpringCGLIB$$ede505eb.CGLIB$templateResolver$3() at com.lh.config.WebConfig$$EnhancerBySpringCGLIB$$ede505eb$$FastClassBySpringCGLIB$$6ff8b31b.invoke() at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) at com.lh.config.WebConfig$$EnhancerBySpringCGLIB$$ede505eb.templateResolver() 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 org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ... 63 common frames omitted

but I dont know why the WebApplicationContext is null

Stefan Wuebbe
  • 2,109
  • 5
  • 17
  • 28
hush
  • 1
  • 3

0 Answers0