我们可以在表单中迭代一组对象:Spring 3.2.5中的radiobuttons吗?
例如在addEmployee.jsp中,
<td><form:radiobuttons path="empDepartmentName" items="${departments}"/></td>
填充部门的方法,
@RequestMapping(value = "/", method = RequestMethod.GET)
public String homePage(ModelMap map) {
map.addAttribute("employee", new Employee());
populateDepartments(map);
return "addEmployee";
}
private void populateDepartments(ModelMap map){
List<String> departments = new ArrayList<String>();
departments.add("Dept 1");
departments.add("Dept 2");
map.addAttribute("departments", departments);
}
部门可以是List<Department>
,并允许客户从UI中选择部门名称,并直接在Employee实体中映射选定的部门,而不是通过瞬态变量empDepartmentName 然后从所选部门名称中获取部门,并将Department对象分配给Employeee并持久保存Employee。我这样做是正确的吗?
@Entity
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String address;
@Transient
private String empDepartmentName;
@OneToOne(fetch=FetchType.LAZY)
private Department department;
}
答案 0 :(得分:0)
为了避免做一个短暂的课 - 取雇员姓名, 您可以使用spring自定义属性编辑器将字符串转换为类型。
自定义属性编辑器可用于将字符串转换为对象类型。 因此,在Employee类上,您可以拥有Department属性,因此不需要empDepName瞬态字段。
这是一个很好的教程 - https://www.credera.com/blog/technology-insights/java/spring-mvc-custom-property-editors/
答案 1 :(得分:0)
你也可以使用这样的转换器(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#core-convert):
public class CategoryConverter implements Converter<String, Category> {
@Autowired
private CategoryService categoryService;
@Override
public Category convert(String id)
{
return categoryService.findById(Integer.parseInt(id));
}
}
并在servlet-config中:
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.app.converters.CategoryConverter" />
</list>
</property>
</bean>
我通常将它与表格一起使用:选择:
<form:select path="department">
<form:options items="${departmentList}" itemValue="id" itemLabel="name" />
</form:select>