Spring MVC Form Processing


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:


@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 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"; } }


<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:

<ol><li>What should I use Editor / Converter?</li> <li>How do I register one of them in my Controller?</li> </ol>


You can register a custom editor into initBinder of your controller class:

@Controller public class CoinViewController { @Autowired private CountryEditor countryEditor; @InitBinder protected void initBinder(final WebDataBinder binder, final Locale locale) { binder.registerCustomEditor(Country.class, countryEditor); } ...... }

(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:

@Component public class CountryEditor extends PropertyEditorSupport { @Autowired private CountryService countryService; @Override public void setAsText(final String text) throws IllegalArgumentException { try{ final Country country = countryService.findById(Long.parseLong(text)); setValue(cliente); }catch(Exception e){ setValue(country); // or handle your exception } } }

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!


  • C# can't read and interpret web API/JSON
  • A pattern for finite (game) state machine in Rust with changing behavior?
  • How I can play two sounds simultaneously in C#
  • C++ coin toss simulator not working
  • How to repaint over images in Java game
  • Using system commands in Perl instead of built in libraries/functions [duplicate]
  • Prolog list not printing all the elements on console
  • Why I have got an error when try save the game ? Unity C#
  • Uncaught TypeError: this.$store.commit is not a function
  • Opening file from a Fileshare-system with python
  • Updating texture not working
  • edge detection iphone opencv
  • Neither BindingResult nor plain target object for bean name 'index' available as request a
  • Add value into request object before validation
  • How can I stub rand in minitest?
  • spring mvc process object before @valid is applied
  • ExtJS 4 Spring 3 file upload. Server sends bad response content type
  • Conditional render in tagfile depending on whether the attribute is specified or not
  • Spring MVC redirect with custom http headers
  • Is MVC2 ASP.Net URLDecoding automatically?
  • Is it mandatory to have a doGet or doPost method?
  • Fragment gives me an error while inflating 1
  • back button function for phonegap windows phone 7
  • Correct implementation of List Iterator methods
  • Implementing “partial void” in VB
  • Sending HTML Form Data to Spring REST Web Service
  • Control modification in presentation layer
  • Trying to switch camera back to front but getting exception
  • what is the difference between the asp.net mvc application and asp.net web application
  • php design question - will a Helper help here?
  • SQL merge duplicate rows and join values that are different
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • Free memory of cv::Mat loaded using FileStorage API
  • How to set the response of a form post action to a iframe source?
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize