我希望有人可以解释一下spring mvc中的转换器。
我的域名类:
@Entity
@Table(name = "TIME_SHEET")
public class TimeSheet implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID_TIME_SHEET")
private Long id;
@NotNull(message = "timesheet.cadastro.horainicio.obrigatorio")
@Temporal(TemporalType.TIME)
@Column(name = "INICIO", nullable = false)
private Date horaInicio;
@NotNull(message = "timesheet.cadastro.horafim.obrigatorio")
@Temporal(TemporalType.TIME)
@Column(name = "FIM", nullable = false)
private Date horaFim;
@Column(name = "LATITUDE", nullable = true)
private Double latitude;
@Column(name = "LONGITUDE", nullable = true)
private Double longitude;
@Size(max = 300,message = "timesheet.cadastro.observacao.acimaDoPermitido")
@Column(name = "OBSERVACAO", nullable = true)
private String observacao;
//@NotNull(message = "timesheet.cadastro.dia.obrigatorio")
@ManyToOne(cascade = javax.persistence.CascadeType.ALL)
@JoinColumn(name = "ID_DIAS")
private Dias dia;
//@NotNull(message = "timesheet.cadastro.usuario.obrigatorio")
@ManyToOne(cascade = javax.persistence.CascadeType.ALL)
@JoinColumn(name = "ID_USUARIO")
private Usuario usuario;
...
我的班级转换器:
public class IdToUsuarioConverter implements Converter<String, Usuario> {
@Autowired
private IusuarioService usuarioService;
public Usuario convert(String id) {
return usuarioService.buscaPorId(Long.valueOf(id));
}
}
在我的springmvc.xml中:
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="br.com.infowhere.timeSheet.converter.IdToUsuarioConverter"/>
</set>
</property>
</bean>
我没有问题,但我的问题是: 1-)当我的转换器发挥作用? 2-)我的.jsp将发布一个表单,其中有一个类似的列表:
<form:select path="user" items="${userList}" multiple="false" />
HTML:
<select id="user" name="user">
<option value="1">User 1</option>
<option value="2">User 2</option>
</select>
我的转换器何时起作用?
我很抱歉,但我正在努力了解转换器。
谢谢!!!
答案 0 :(得分:1)
您的转换器会将ID转换为控制器中的Usario对象。 例如:
@Controller
public class MyController {
@RequestMapping("/showUsario")
public String showUsario(@RequestParam("id") Usario usario, Model model) {
model.addAttribute("usario", usario);
return "showUsario";
}
}
然后对/ showUsario?id = 123的请求将使用转换器将字符串“123”转换为Usario。如果您没有转换器,则必须在方法参数中放置String id(而不是Usario)并手动将id转换为Usario。通过这种方式,Spring可以为您使用转换器。