我在一个页面中使用一个托管bean进行拖动命令。第一种方法创建一个游览,第二种方法为该游览添加照片网址。但问题是,当我调用第二种方法时,我创建的游览将丢失并返回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)$/" />
答案 0 :(得分:0)
您可以使用this
关键字。它是对当前对象的引用。但是如果在调用setter方法之前未初始化此当前对象,则会得到NullPointerException
。因此,我提议在构造函数中初始化tour
对象或始终首先调用execute()
方法。我修改了你的代码,但我没有初始化巡视,因为这是你的决定:
@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();
}
}
我希望这段代码对您有所帮助!