Halil
Halil

Reputation: 2317

Spring MVC - Conditionally return html content or template content

I want to return HTML content(which is provided from an external service), when payment transaction completed successfully.

If payment transaction fails, I want to return to payment form(which is a thymeleaf template).

How can I implement this conditional behaviour?

@PostMapping(value =  "/payment3ds/{offerId}/{company}")
public String payment3dsPost(
                             @PathVariable(value = "offerId") String offerId,
                             @PathVariable(value="company") String companyName,
                             @ModelAttribute("startSubscriptionRequest") StartSubscriptionRequest formInput, Model model) {

    try {
        String htmlContent = endpointsNoAuth.startSubscription3ds(formInput);

        return htmlContent; // value: "<html><body>...</body><html>
    } catch (IllegalArgumentException e) {
        Offer plan = subscriptionPlanRepo.findOneByIdAndCompanyName(Long.valueOf(offerId), companyName);
        model.addAttribute("subscriptionPlan", plan);
        model.addAttribute("errorText", e.getMessage());

        return "payment3ds"; // thymeleaf template
    }
}

Upvotes: 2

Views: 598

Answers (1)

Halil
Halil

Reputation: 2317

To resolve this issue, first I developed a new implementation of View interface. This implementation will be used to return HTML code to client:

public class HtmlView implements View {
    private String src;

    public HtmlView(String htmlContent) {
        this.src = htmlContent;
    }

    @Override
    public String getContentType() {
        return MediaType.TEXT_HTML_VALUE;
    }

    @Override
    public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse response) throws Exception {
        response.setContentType(getContentType());
        response.getWriter().append(src);
    }
}

Then I updated my controller to return ModelAndView:

@PostMapping(value =  "/payment3ds/{offerId}/{company}")
public ModelAndView payment3dsPost(...) {

    try {
        String htmlContent = "<html></html>";
        View view = new HtmlView(htmlContent);
        modelAndView.setView(view);

        return modelAndView;
    } catch (IllegalArgumentException e) {
        Offer plan = subscriptionPlanRepo.findOneByIdAndCompanyName(Long.valueOf(offerId), companyName);
        Company company = companyRepo.findByName(companyName);

        // Add your data in model
        Map<String, Object> model = modelAndView.getModel();

        modelAndView.setViewName("payment3ds"); // thymeleaf template
        return modelAndView; 
    }
}

If I want to return HTML code, I use an HtmlView, otherwise I use the name of the template in ModelAndView object.

Upvotes: 1

Related Questions