1

我在使用一个托管 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();
}

xml相关部分:

<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)$/" />  
4

1 回答 1

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();
}
}

我希望这段代码对你有帮助!

于 2013-10-20T17:06:55.737 回答