Spring MVC Form Processing

2019-09-06 08:50发布

问题:

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:

  1. What should I use Editor / Converter?
  2. How do I register one of them in my Controller?

回答1:

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!