我在一个页面中使用一个托管 Bean 的 tow 命令。 第一种方法创建一个游览,第二种方法将照片 URL 添加到该游览中。 但问题是,当我调用第二个方法时,我创建的 Tour 会丢失并返回 null。 我该如何解决这个问题?
@ManagedBean(name="addtour")
@SessionScoped
public class CreateTourAction {
private Tour tour;
public String execute() {
tour = new Tour(this.date,this.province,this.country, this.category,transportation,this.gregarious,this.days, this.space,BigDecimal.valueOf(price));
tour.save();
return"success";
}
public void handleFileUpload(FileUploadEvent event) {
tour.setImg_urls(urls);
tour.save();
}
XTML相关部分:
<h:commandButton value="Create" action="#{addTour.execute}"/>
<p:fileUpload fileUploadListener="#{addTour.handleFileUpload}" mode="advanced" dragDropSupport="true"
update="messages" sizeLimit="1000000" fileLimit="3" allowTypes="/(.|/)(gif|jpe?g|png)$/" />
您可以使用
this
关键字。它是对当前对象的引用。但是,如果在调用setter方法之一之前未初始化此当前对象,则NullPointerException
。因此,我建议在构造函数中初始化tour
对象,或者始终首先调用execute()
方法。我修改了您的代码,但我不初始化 tour,因为这是您的决定:
@ManagedBean(name="addtour")
@SessionScoped
public class CreateTourAction {
private Tour tour;
public String execute() {
this.tour = new Tour(this.date,this.province,this.country, this.category,transportation,this.gregarious,this.days, this.space,BigDecimal.valueOf(price));
this.tour.save();
return"success";
}
public void handleFileUpload(FileUploadEvent event) {
if(this.tour != null){
this.tour.setImg_urls(urls);
this.tour.save();
}
}
我希望这段代码对您有所帮助!