Spring MVC将id绑定到Model中的对象

时间:2012-08-23 21:17:38

标签: spring-mvc binding

代码如下所示:

传感器类:

@Entity
@Table(name = "sensor")
public class Sensor {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne
private SensorType sensorType;

@NotEmpty
@Size(min = 3, max = 255)
@Column(name = "name")
private String name;
    ......
}

SensorType:

@Entity
@Table(name = "sensortype")
public class SensorType {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column(name = "type")
private String type;
    ......
}

当我尝试插入新传感器时出现错误,SensorType为null 因为我只是从jsp向SensorController发送SensorType“id” 并且控制器需要一个SensorType对象。

SensorController:

@Controller
public class SensorController {

@Autowired
private ISensor sensorService;

@RequestMapping(value = "/sensor/add", method = RequestMethod.POST)
public String add(Sensor sensor, BindingResult result, Model model) {

     if (result.hasErrors()) {
                return "sensorAdd";
             }       

     sensorService.insert(sensor);
     return "redirect:/sensors";
  }
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

解决此问题的一种典型方法是以这种方式指定转换器:

public class IdToSensorTypeConveter implements Converter<Integer, SensorType>{
    ...
    @Override
    public SensorType convert(Integer id) {
        return this.sensorTypeDao.findById(id);
    }

}

使用Spring注册此转换器:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="IdToSensorTypeConveter"/>
        </set>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService"/> 

现在,如果您提交的表单在传感器字段中有一个sensorType字段,它将自动绑定到上述转换器返回的sensorType。