That was a stupid and weird problem that I’ve encountered so far.
I’m gonna show you that was the root cause after all my time have spent to revert and check all the code 1 by 1. Before that, you need to ensure that your resources configuration and your thymeleaf view is set properly. Such as your context setting.
@Configuration @ComponentScan(basePackages="com.codeomitted") @EnableWebMvc public class MvcConfiguration extends WebMvcConfigurerAdapter{ @Bean public TemplateResolver templateResolver() { TemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); templateResolver.setCacheable(false); return templateResolver; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver(); thymeleafViewResolver.setTemplateEngine(templateEngine()); thymeleafViewResolver.setCharacterEncoding("UTF-8"); return thymeleafViewResolver; } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new SpringSecurityDialect()); return templateEngine; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); }
View
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title th:text="#{view.index.title}">Test!</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link href="" rel="stylesheet" media="screen" th:href="@{/resources/css/bootstrap.min.css}"/> <script src="" th:src="@{/resources/js/bootstrap.min.js}"></script> </head> <!-- //codeomitted -->
After all the setting is configured properly but still pages not render properly, then check your controller @RequestMapping. My problem was caused by the following code:
@ModelAttribute("tokenform") public TokenForm getCommandObject() { return new TokenForm(); } @RequestMapping(method=RequestMethod.GET) public String index() { return "/tokenform"; }
The code still able to run and render the page, but just not able to display all the css, javascript files. Change the @RequestMapping and add the value parameters.
@ModelAttribute("tokenform") public TokenForm getCommandObject() { return new TokenForm(); } @RequestMapping(value="/", method=RequestMethod.GET) public String index() { return "/hnapay/tokenform"; }
Now everything run fine. I do not have any idea why this happen properly you can answer and let me know the issues.