Spring MVC表单处理 [英] Spring MVC Form Processing

查看:82
本文介绍了Spring MVC表单处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先:我是Spring的初学者,这是我第一次尝试使用Spring MVC实现Web应用程序. 这是我已经完成的事情:

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

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>

但是,当我尝试保存JSP的输入时,总是会得到以下提示:

But when I try to save the input from the JSP I always get this:

"country"字段上的"coin"对象中的字段错误:拒绝的值[1]; 密码 [typeMismatch.coin.country,typeMismatch.country,typeMismatch.Country,typeMismatch]; 论点 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码[coin.country,country];参数[];预设讯息 [国家]];默认消息[无法转换类型的属性值 'java.lang.String'为属性'country'的必需类型'Country'; 嵌套的异常是java.lang.IllegalStateException:无法转换 类型[java.lang.String]的值更改为所需的[Country]类型 属性国家/地区":找不到匹配的编辑器或转换策略]

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]

所以我的问题是:

  1. 我应该使用什么编辑器/转换器?
  2. 如何在我的控制器中注册其中之一?

推荐答案

您可以将自定义编辑器注册到控制器类的initBinder中:

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参数,但是如果您需要使用语言环境进行转换,例如在使用日期时,该参数很有用)

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

,您可以定义您的CountryEditor,如下所示:

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

我让spring用@Component注释处理编辑器的注入.因此,如果您喜欢这种方式,请记住为该类启用程序包扫描!

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!

希望获得帮助!

这篇关于Spring MVC表单处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆