Issue
public class ProcessHtmlUtil {
@Autowired
TemplateEngine htmlTemplateEngine;
public String processHTML(){
try {
final Context ctx=new Context();
return htmlTemplateEngine.process("Redoc-Integrate.html",ctx);
}
catch(RuntimeException e){
log.error("Runtime exception occurred: {}", e.getMessage());
throw e;
} catch(Exception e){
log.error("Internal processing error occurred: {}", e.getMessage());
throw new InternalServerException("Internal processing error");
}
}
}
Above is code placed in a class, this is supposed to be returning html string to controller method. And Controller from there having some headers would be returning output as HTML page. But certainly this is not happening, and the htmlTemplateEngine.process giving NuLLPointer exception. But this is not happening when whole content is present in controller method. Below is code in controller when whole code is not in controller
@GetMapping(value = "/v1/redoc")
public ResponseEntity<?> gotoRedocUi(){
ProcessHtmlUtil processHtmlUtil=new ProcessHtmlUtil();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=UTF-8");
return new ResponseEntity<>(processHtmlUtil.processHTML(),responseHeaders, HttpStatus.OK); // return html file defined in resources/templates.
}
Also code to resolver
@Bean
public TemplateEngine htmlTemplateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
private ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setResolvablePatterns(Collections.singleton("html/*"));
templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding("utf-8");
templateResolver.setCacheable(false);
return templateResolver;
}
}
Solution
It was bean instantiation issue.
@GetMapping(value = "/v1/redoc")
public ResponseEntity<?> gotoRedocUi(){
ProcessHtmlUtil processHtmlUtil=new ProcessHtmlUtil();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=UTF-8");
return new ResponseEntity<>(processHtmlUtil.processHTML(),responseHeaders, HttpStatus.OK); // return html file defined in resources/templates.
}
Now the stuff that I din notice was ProcessHtmlUtil processHtmlUtil=new ProcessHtmlUtil(); so need to autowire it inspite of using new. else beans are not getting populated. So yeah thats it, that was bean instantiation error.
Answered By - naruto
Answer Checked By - Mary Flores (JavaFixing Volunteer)