First of all: I'm a beginner in Spring and this is my first try to implement an web application with Spring MVC. Here is what I've done yet:
Entities:
@Entity
@Table(name = "coins")
public class Coin
{
@Id
@GeneratedValue
private Integer id;
@OneToOne
private Country country;
private double value;
private int year;
}
@Entity
@Table(name = "countries")
public class Country
{
@Id
@GeneratedValue
private Integer id;
private String name;
}
Controller:
@Controller
public class CoinViewController {
@Autowired
private CoinService service;
@Autowired
private CountryService countryService;
@ModelAttribute("countries")
public List<Country> frequencies() {
return countryService.get();
}
@RequestMapping(value = "/coins/add", method = RequestMethod.GET)
public String addCoin(Model model) {
model.addAttribute("coin", new Coin());
return "coins/add";
}
@RequestMapping(value = "/coins/add", method = RequestMethod.POST)
public String addCoinResult(@ModelAttribute("coin") Coin coin, BindingResult result) {
// TODO: POST HANDLING
return "/coins/add";
}
}
JSP:
<form:form action="add" method="POST" modelAttribute="coin">
<div class="form-group">
<label for="country">Country:</label>
<form:select path="country" class="form-control" >
<form:option value="" label="-- Choose one--" />
<form:options items="${countries}" itemValue="id" itemLabel="name" />
</form:select>
</div>
<div class="form-group">
<label for="value">Value:</label>
<form:input path="value" class="form-control" />
</div>
<div class="form-group">
<label for="year">Year:</label>
<form:input path="year" class="form-control" />
</div>
<button type="submit" value="submit" class="btn btn-default">Erstellen</button>
</form:form>
But when I try to save the input from the JSP I always get this:
Field error in object 'coin' on field 'country': rejected value [1]; codes [typeMismatch.coin.country,typeMismatch.country,typeMismatch.Country,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [coin.country,country]; arguments []; default message [country]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'Country' for property 'country'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [Country] for property 'country': no matching editors or conversion strategy found]
So my questions are:
- What should I use Editor / Converter?
- How do I register one of them in my Controller?
You can register a custom editor into initBinder of your controller class:
(
locale
parameter is not needed in this case, but it can be useful if you need locale to make conversion - for example if you are working with dates)and you can define your
CountryEditor
like the following:I let spring handle injection of my editors with
@Component
annotation. So if you like to do in that way remember to enable package scan for that class!Hope this help!