Greetings, I have a page where you must make records of an employee in which an attribute is an object (relationship with another table) and to specify it is done by a select that this time I use the Spring but I get the Next error in validation.
Failed to convert property value of type java.lang.String to required type com.edw.model.Position for property position;
nested exception is java.lang.IllegalStateException:
Cannot convert value of type java.lang.String to required type
com.edw.model.Position for property position: no matching editors or
conversion strategy found
This error is shown in the view when it makes the validations, in the tomcat console it does not say anything, this is what I have in the configuration of Spring for the conversions.
<mvc:annotation-driven />
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<ref bean="positionFormatter" />
</set>
</property>
</bean>
This is the converter
@Component
public class PositionFormatter implements Formatter<Position> {
@Autowired
private PositionService positionService;
@Override
public String print(Position arg0, Locale arg1) {
return arg0.getPositionName();
}
@Override
public Position parse(String arg0, Locale arg1) throws ParseException {
try {
Integer id = Integer.parseInt(arg0);
return positionService.getById(id);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The class Empleado
has an object attribute that is the class Position
which in turn contains the id attribute
This is the code fragment of the jsp page where all the available charges are shown by a selection
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<label for="position">Cargo *</label>
<f:select path="position" class="form-control" id="position">
<f:option value="${null}" label="Seleccione..."></f:option>
<f:options items="${positions}" itemLabel="positionName" itemValue="id"/></f:select>
<f:errors path="position" cssClass="text-danger"></f:errors>
This is the driver:
@Autowired
private ConversionService conversionService;
@RequestMapping(value = "/guardar", method = RequestMethod.POST)
public String save(@Valid final Employee employee, BindingResult result, Model model) {
if(result.hasErrors()) {
try {
List<Position> positions = positionService.getAll();
model.addAttribute(positions);
} catch (Exception e) {
e.printStackTrace();
}
return "empleados/registro";
}
try {
employeeService.create(employee);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/index";
}
@InitBinder
public void registerConversionServices(WebDataBinder dataBinder) {
if(dataBinder.getConversionService() == null)
dataBinder.setConversionService(conversionService);
}
Even removing the @Valid
keeps throwing the error, thanks in advance.
PS: When you show the view again with validation errors thrown, the list of charges in select
is not displayed.