Search code examples
javaspring-bootspring-restspring-validator

Return a thymeleaf view conditionally with PDF view in Spring MVC handler


I am developing a spring boot application & using spring validation. Need to return a thymeleaf page if any error occurs after validation.

@ResponseBody
@PostMapping(params = "_action_preview_pdf", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<byte[]> getTemplatePDF(@Valid @ModelAttribute(COMMAND_NAME) RxTemplateConfiguration configuration,
                                             BindingResult result) {

    if(result.hasErrors()){
        return VIEW_FORM;  //Error
    }

    ....

    return new ResponseEntity<>(prescriptionHelper.getTemplatePdf(configuration), headers, HttpStatus.OK);

}

getting following error:

error: return VIEW_FORM; incompatible types: String cannot be converted to ResponseEntity<byte[]>

Here, VIEW_FORM = "config-form" which is a thymeleaf page. How can I return thymeleaf page?


Solution

  • Solution:

    1. Removed @ResponseBody tag.
    2. Replaced return type from ResponseEntity<byte[]> to Object

    Code after update:

    @PostMapping(params = "_action_preview_pdf", produces = MediaType.APPLICATION_PDF_VALUE)
    public Object getTemplatePDF(@Valid @ModelAttribute(COMMAND_NAME) RxTemplateConfiguration configuration,
                                             BindingResult result) {
    
        if(result.hasErrors()){
            return VIEW_FORM;  //Error fixed.
        }
    
        ....
    
        return new ResponseEntity<>(prescriptionHelper.getTemplatePdf(configuration), headers, HttpStatus.OK);
    
    }