弹簧MVC绑定id来的对象在一个模型 [英] Spring MVC bind id to an object in a Model

查看:130
本文介绍了弹簧MVC绑定id来的对象在一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code是这样的:

传感器类:

@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:

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发送SensorTypeID到SensorController
和所述控制器被期待一个SensorType对象

I get an error when I try to insert a new Sensor, SensorType is null because I'm only sending the SensorType "id" to SensorController from jsp and the controller is expecting a SensorType object.

SensorController:

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";
  }
}

我该如何解决呢?

How can I solve this?

推荐答案

解决这个的典型方法是指定一个转换器,这种方式:

A typical way of solving this is to specify a converter, this way:

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

}

中注册此转换器,弹簧:

Register this converter with 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。

Now, if your submitted form has a field for sensorType in sensor fields, it will automatically be bound to the sensorType returned by the above converter.

这篇关于弹簧MVC绑定id来的对象在一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆