Issue
Please find this project on GITHUB as studentsbooks
I am getting errror as below, even after following a proper tutorial. Kindly guide where i am going wrong. Feel free to clone the project. Committed Just now.
2021-04-23 20:45:38.227 INFO 16580 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] :
Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-04-23 20:45:38.227 INFO 16580 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-04-23 20:45:38.229 INFO 16580 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
2021-04-23 20:45:38.259 WARN 16580 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /WEB-INF/jsp/login.jsp
Solution
I created a class InsertInitialData class annotated as @Component
and used WebApplicationContext
with autowired
annotation. Thymeleaf uses context to get initialized please find in below code.
@Component
public class InsertInitialData{
WebApplicationContext context;
@Autowired
public void setContext(WebApplicationContext context) {
this.context = context;
}
@Bean //as it is from thymeleaf documentation, just passed the context! else is same!
public SpringResourceTemplateResolver templateResolver(){
// SpringResourceTemplateResolver automatically integrates with Spring's own
// resource resolution infrastructure, which is highly recommended.
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.context);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
// HTML is the default value, added here for the sake of clarity.
templateResolver.setTemplateMode(TemplateMode.HTML);
// Template cache is true by default. Set to false if you want
// templates to be automatically updated when modified.
templateResolver.setCacheable(true);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
// SpringTemplateEngine automatically applies SpringStandardDialect and
// enables Spring's own MessageSource message resolution mechanisms.
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// Enabling the SpringEL compiler with Spring 4.2.4 or newer can
// speed up execution in most scenarios, but might be incompatible
// with specific cases when expressions in one template are reused
// across different data types, so this flag is "false" by default
// for safer backwards compatibility.
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
Take a look at the repo, clone and run, using Spring boot run
Answered By - Abhijeet
Answer Checked By - David Goodson (JavaFixing Volunteer)