0
votes

I am having trouble passing args from html to spring mvc 4 controller using thymeleaf 3.

Here is the controller:

// Handler method for inserting currency:
@RequestMapping(value = "/saveCurrency", method = RequestMethod.POST)
public ModelAndView saveCurrency(@ModelAttribute("currency") Currency currency, BindingResult bindingResult, Model model)
{
    model.addAttribute("currency", currency);
    currDAO.insert(currency);

    return new ModelAndView("redirect:/listCurr");
}

And html form:

<form action="/saveCurrency" th:action="@{/saveCurrency}" th:object="${currency}" th:method="post">
    <input id="nameTB" type="text" th:field="*{name}" class="form-control" maxlength="3" style="text-transform:uppercase" />
    ...
</form>

I also have the class Currency with fields "id" and "name" and with getters and setters for them. Now with this code I get an error:

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/listCurr.html]")] with root cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'currency' available as request attribute

Any idea what am I doing wrong?

2

2 Answers

1
votes

The issue is that model attribute is not set previously. You'll need some request mapping method to set your model attribute:

@RequestMapping(value = "/currency", method = RequestMethod.GET)
public String currencyPage(Model model) {
    model.addAttribute("currency", new Currency());
    return "listCurr";
}

Sidenotes: In your method, you don't need to set "currency" model attr. again. Also, you want to check if BindingResult has errors before you save your currency:

if(!bindingResult.hasErrors()) {
    currDAO.insert(currency);
}
0
votes

Don't redirect,return model with view.

model.addAttribute("currency", currency);
return new ModelAndView("listr");