JasperException:java.lang.IllegalStateException:BindingResult和bean名称'user'的普通目标对象都不可用作请求属性

时间:2017-03-11 22:02:37

标签: spring spring-mvc

我有两个数据模型:用户和车,用户可以有很多车,所以这是用户类:

@Entity
@Table(name="APP_USER")
public class User implements Serializable{

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

@OneToMany(mappedBy="user",cascade=CascadeType.ALL)
private Set<Car> cars = new HashSet<Car>();

Car.java:

@Entity
public class Car implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id ;
.....

@ManyToOne(optional=false)
@JoinColumn(name="user_fk")
private User user;

在carController中,我有为一个用户添加新Car的方法:

@Controller
@RequestMapping("/cars")
public class CarController {

@Autowired
CarService carService;

@Autowired
UserService userService;

@RequestMapping(value={"/list"},method=RequestMethod.GET)
public String listCars(ModelMap model){
List<Car> cars = carService.allCars();
model.addAttribute("cars", cars);
return "car"; }

@ModelAttribute("utilisateurs")
public List<User> allUsers(){
List<User> utilisateurs = userService.findAllUsers();
return utilisateurs;
}  


@RequestMapping(value={"/newCar"},method=RequestMethod.GET)
public String newCar(ModelMap model){

Car car = new Car();
model.addAttribute("car",car);
return "carRegistration";
}

@RequestMapping(value={"newCar"},method=RequestMethod.POST)
public String newCar(@Valid Car car, BindingResult result,ModelMap model){

if (result.hasErrors()) {
    return "registration";
}
carService.save(car);
model.addAttribute("car",car);

return "redirect:/cars/list";
}

最后,在视图中,表单为:

<form:form method="POST" modelAttribute="car"
                            class="form-horizontal">

      <form:input type="hidden" path="id" id="id" />

      <div class="control-group">
        <label class="control-label">Libelle</label>
        <div class="controls">
          <form:input type="text" path="libelle" id="libelle" style="height:4%" />
        </div>
      </div>
      <div class="control-group">
        <label class="control-label">Registration</label>
        <div class="controls">
          <form:input type="text" path="registration" id="email" />
        </div>
      </div>



      <div class="control-group">
        <label class="control-label">Utilisateur</label>
        <div class="controls">
          <form:select path="user" items="${utilisateurs}"  itemValue="id" itemLabel="lastName" style="margin-left: 4%;"></form:select>
        </div>
      </div>   

      <div class="form-actions">
        <input type="submit" value="Validate" class="btn btn-success" />
      </div>

    </form:form>

我可以获得视图,但是当我点击按钮提交时,我收到此错误:

Neither BindingResult nor plain target object for bean name 'user' available as request attribute.

我认为选择用户项有问题!!

1 个答案:

答案 0 :(得分:0)

您是否为用户提供了任何Spring转换器或格式化程序?

的applicationContext.xml:

 <bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="my.project.StringToUser"/>
            <bean class="my.project.StringToRole"/>

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

它会将用户ID转换为用户对象。

my.project.StringToUser:

import org.springframework.core.convert.converter.Converter;

public class StringToUser implements Converter<String, JUser> {

  @Autowired
  private UserService userService;

  @Override
  public JUser convert(String source) {
      long id = Long.valueOf(source);
      return userService.get(id);
  }
}

错误:

WARNING: Failed to bind request element: org.springframework.beans.TypeMismatchException: 
    Failed to convert value of type [com.websystique.springmvc.model.User] to required type [com.websystique.springmvc.model.User]; 
nested exception is org.springframework.core.convert.ConversionFailedException:
  Failed to convert from type [com.websystique.springmvc.model.User] to
  type [@org.springframework.web.bind.annotation.ModelAttribute @javax.validation.Valid com.websystique.springmvc.model.User] 
  for value 'User [id=null, ssoId=alaa, password=alaa1991, firstName=, lastName=, email=, userProfiles=null, accounts=null, userDocuments=[], cars=[], documents=[]]';
nested exception is java.lang.ClassCastException: 
   com.websystique.springmvc.model.User cannot be cast to java.lang.String