4.1spring mvc 出现“Failed to convert property value of type”解决方法
这个问题分成两类
String转换为基本类型(int,long,boolean,char...)对与这类可以在controller的高层添加一个静态方法
@InitBinderprotected void init(HttpServletRequest request, ServletRequestDataBinder binder) throws WebSysErrException {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, false));//initDataBinder(request, binder);}?这样就可以解决一般string和date之间的转换。
string与自定义实体之间的转换先描述一下:这个是一个entity
@SuppressWarnings("serial")@MappedSuperclasspublic abstract class BaseArticle<T, PK> extends ModelSupport<T, PK> {@NotEmpty(message = "内容不能为空")@Column(name = "content")private String content;@ManyToOne(optional = true)@JoinColumn(name = "category_id")private Category category;?在jsp中,用以下方法将其取出:
文章类别:<form:select path="category"><form:option value="">--请选择文章分类--</form:option><form:options items="${categories}" itemValue="id" itemLabel="name"/></form:select>?但是 可以遇见,在submit后post中的category字段是一个string类型,springmvc肯定不知道如果得到索要的categroy,所以会报以下错误:
Failed to convert property value of type 'java.lang.String' to required type
?接下来是解决方法:
- 创建自定义转换器
?
public class CategoryEditor extends PropertyEditorSupport {public CategoryEditor(CategoryServ categoryServ) {super();this.categoryServ = categoryServ;}@Overridepublic void setAsText(String text) throws IllegalArgumentException {if(!StringUtils.isBlank(text)) {Category category = categoryServ.load(Long.parseLong(text));setValue(category);}} //这个是业务层的服务类,按理说这个应该会被spring注入,但是经过我的测试, //无论是使用@autowired还是直接实例化,其均为null。 //所以,必须在control中给其传递一个server!!!!private CategoryServ categoryServ; }?controller中的写法:
CategoryEditor categoryEditor = new CategoryEditor(categoryServ);binder.registerCustomEditor(Category.class, categoryEditor);
?
这样就可以保证server是可以工作的了。