提问人:Andrzej Więcławski 提问时间:9/11/2021 最后编辑:Andrzej Więcławski 更新时间:9/12/2021 访问量:136
Spring 可以解码@ModelAttribute它是否包含 Long 字段还是 Map 实例?
Could Spring decode @ModelAttribute if it contains Long field or is a Map instance?
问:
除了传递 java 对象之外,还有其他方法:@SessionAttributes("entitytopass")
来自“form”servlet / controller ->的 POST 方法
->到“显示”的那个,
如果它包含长字段还是 Map 实例?
经过多次尝试,用于传递,例如:RedirectAttributes redirectAttributes
Entity entity
redirectAttributes.addAttribute("entitytopass", entity);
我惊讶地发现它持续解析从 Long 到 Integer 1 的字段。这会导致无法在接收 Servlet 中构建接收到的对象。因此,下面的方法不成功并抛出:TypeMismatchException
@RequestMapping(value ="/display", method = RequestMethod.GET)
public String add(@ModelAttribute("entitytopass") Entity entityreceived, Model model) {
model.addAttribute("entitypresented", entityreceived);
return "/displaypage"; // displaypage.jsp would present saved values
}
解码后的 Spring 错误报告为:Entity entityreceived
Failed to convert value of type 'java.lang.String' to required type 'some.domain.jpa.model.Entity';
nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.ModelAttribute some.domain.jpa.model.Entity] for value '0';
nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Provided id of the wrong type for class some.domain.jpa.model.Entity. Expected: class java.lang.Long, got class java.lang.Integer;
nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class some.domain.jpa.model.Entity. Expected: class java.lang.Long, got class java.lang.Integer
如果实体是实例,则相同的 happans,尽管从会话中传输和提取的对象经过编码和解码,没有任何问题 beetween servlet / 控制器。Map<String,String>
--编辑--
实体是象征性的,但例如。
public class Entity extends BaseEntity implements Serializable, EntityLabels {
private static final long serialVersionUID = -3776095967033917869L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "addr_id")
private long addressId;
@Column(updatable = true, name = "addr_name", nullable = true, length = 50)
private String addressName;
@Column(updatable = true, name = "city", nullable = false, length = 50)
private String city;
@Column(updatable = true, name = "post_cod", nullable = false, length = 6)
private String postalCode;
@Column(updatable = true, name = "street", nullable = false, length = 50)
private String streetName;
@Column(updatable = true, name = "str_no", nullable = false, length = 6)
private String streetNumber;
@Column(updatable = true, name = "flat_no", nullable = true, length = 6)
private String flatNumber;
@ColumnDefault(value = "'Poland'")
@Column(updatable = true, name = "country", nullable = false, length = 50)
private String country; // = "Poland";
// standard constructor
public Entity() {
}
// getters & setters
}
答:
评论
Entity