Mavens,
I am struggling to invoke a controller from Themeleaf.
My themeleaf code looks like:
<form action="#" th:action="@{/order}" modelAttribute="order" th:object="${order}" method="POST">
<div class="div">
<h5>Amount</h5>
<input type="text" class="input" th:field="*{amountValue}">
</div>
<input type="submit" class="btn" value="Process Payment">
</form>
My Controller Code is:
@RequestMapping(value = "/order", method = RequestMethod.POST)
public ModelAndView processOrder(@ModelAttribute Order order) {
ModelAndView modelAndView = new ModelAndView();
String accessToken = token();
String paymentURL = null;
if (accessToken != null) {
paymentURL = placeOrder(accessToken, order);
if (paymentURL != null) {
modelAndView.addObject("orderReferenceNumber", paymentURL.substring(paymentURL.indexOf("=") + 1));
modelAndView.addObject("paymentURL", paymentURL + "&slim=true");
modelAndView.setViewName("paymentProcess");
return modelAndView;
}
}
return modelAndView;
}
My Get method is
@RequestMapping(value = "/index", method = RequestMethod.POST)
public ModelAndView doLogin(@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "password", required = true) String password) {
ModelAndView modelAndView = new ModelAndView();
if (username != null && password != null) {
if (username.equalsIgnoreCase("one") && password.equalsIgnoreCase("one")) {
modelAndView.addObject("order", new Order());
modelAndView.setViewName("index");
return modelAndView;
}
}
modelAndView.setViewName("welcome");
return modelAndView;
}
Error on click of the button
Error resolving template [order], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [order], template might not exist or might not be accessible by any of the configured Template Resolvers
What am i doing wrong ?
The issue comes from how you populate your
ModelAndViewinstance. Only when your twoifclauses are matched, you set the name of the view withmodelAndView.setViewName("paymentProcess");. That means for some executions (not matching your both conditionals), you don't set the name of the view at all and Spring MVC doesn't know which view to render and return to the user.To fix this, make sure you always set a default/fallabck view to return in case the
ifconditions are both nottrue. Your code might override this view name but you have at least for each case a view to fallback on: