How to Call a WebController From a RestController And Get A Rendered Template in Response in String In Java

136 views Asked by At

I have invoice-service written in java (Spring Framework) where there are two controllers-

  1. InvoicePageController - Annotated with @Controller annotation and a handler generateInvoice inside it which returns a view 'invoice' a html template in the service
  2. InvoiceController - Annotated with @RestController annotation and a handler getInvoiceUrl which is supposed to return url of an invoice uploaded to s3

The InvoiceController will get some data in the Request and that data I am passing to InvoicePageController by doing a Rest Call to to same service InvoicePageController class and getting the rendered view in response and stored in a string variable

Now the string which I got in response, I am uploading to S3 and getting it's URL and sending it in the response

Question - I am doing a network call to get the rendered invoice template , If I do a direct call to the method of InvoicePageController then instead of a rendered view I will get the simple 'invoice' string in reponse, So I wanted to know is there a way to get the rendered view with doing the network call

Below is the classes

InvoicePageController.java

@Controller
@RequestMapping(path = "/invoice-page")
public class InvoicePageController {

  @PostMapping
  public String getInvoicePage(@RequestBody InvoiceRequest request, Model model) {

    model.addAttribute("labDetails", request.getLabDetails());
    model.addAttribute("order", request.getOrder());
    model.addAttribute("orderItems", request.getOrderItems());
    return "invoice";
  }
}

InvoiceController.java

@RestController
@RequestMapping(path = "/invoice")
public class InvoiceController {
  
  @Autowired RestHelper restHelper;
  @Autowired S3Service s3Service;

  @PostMapping
  public ResponseEntity<String> getInvoiceUrl(@RequestBody InvoiceRequest request) {
    // Call to a helper method with the payload to get the rendered invoice in the string variable
    String invoicePage = restHelper.getInvoicePage(request);
    String invoiceUrl = s3Service.uploadToS3AndGetUrl(invoicePage);
    return new ResponseEntity<>(invoiceUrl, HttpStatus.OK);
  }
}

Note -

  1. I am using thymeleaf for view rendering
  2. Upon doing the network call the rendered view comes as string properly

Query - Is there a way to get the rendered view directly instead of doing a network call

0

There are 0 answers