Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将一个托管bean用于两个方法并将数据保存在变量中?_Java_Jsf 2_Primefaces - Fatal编程技术网

Java 如何将一个托管bean用于两个方法并将数据保存在变量中?

Java 如何将一个托管bean用于两个方法并将数据保存在变量中?,java,jsf-2,primefaces,Java,Jsf 2,Primefaces,我在一个页面中有两个使用一个托管bean的命令。第一个方法创建一个巡更,第二个方法向该巡更添加照片URL。但问题是,当我调用第二个方法时,我创建的tour丢失并返回null。我怎样才能解决这个问题 @ManagedBean(name="addtour") @SessionScoped public class CreateTourAction { private Tour tour; public String execute() { tour = new Tour(this.date,

我在一个页面中有两个使用一个托管bean的命令。第一个方法创建一个巡更,第二个方法向该巡更添加照片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)$/" />  

您可以使用
这个
关键字。它是对当前对象的引用。但如果在调用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();
}
}

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

So
tour.setImg_URL(URL)
将抛出一个
NullPointerException
?到目前为止,代码看起来还不错,请尝试调试并找出这两个请求的bean是否仍然相同。bean也应该是可序列化的。是的,我知道。在您的情况下,当第一次调用
handleFileUpload
时,此
tour
null
。当然,
这个
并没有解决您的问题,但我在回答中描述了您需要在构造函数或字段中初始化:
私人巡更更改为
私人巡更=新巡更()