我是JavaBeans的新手,我需要一些帮助来保持我的第一个小型JSF项目。
我正在编写一个小型Web应用程序,用户可以使用某些建筑标准进行搜索。因此,用户输入搜索表单“位置”,“房产类型”,“要价”,“房间数量”和“生活空间”。
我的托管bean接受使用setter / getter的查询,现在数据将被传输到SQL类,在那里处理它们并返回匹配的搜索结果。这听起来很简单,但我找不到解决方案。
我的托管bean现在看起来像这样:
package beans
//import statements
...
@ManagedBean
@RequestScoped
public class PropertySearchBean {
private String _place
private String _propertyType
private double _askingPrice
private int _rooms
private double _livingSpace
public ArrayList<SearchResults> results = new ArrayList<SearchResults>();
// empty constructor
...
// getter and setter for these 5 user inputs
...
public void initializeSearchResults() {
// do the SQL query, recieve search results
// add it as a new object of 'SearchResults'
SQLPropertySearch search = new SQLPropertySearch(_place, _propertyType,
_askingPrice, _rooms, _livingSpace);
ArrayList<Integer> idResults = search.getPropertyIDlist();
SQLProperty property;
if(!idResults.isEmpty()) {
for(int i=0; i<idResults.size(); i++) {
property = new SQLProperty(idResults.get(i));
results.add(new SearchResults(
property.getPropertyID(),
property.getPropertyName(),
// and so on..
));
}
}
}
public static class SearchResults {
int propertyID;
String propertyName;
// and so on..
public SearchResults(int propertyID, String propertyName) {
this.propertyID = propertyID;
this.propertyName = propertyName;
// and so on..
}
// getter and setter
public int getPropertyID() {
return propertyID;
}
public void setPropertyID(int propertyID) {
this.propertyID = propertyID;
}
// and so on..
}
public ArrayList<SearchResults> getResults() {
return results;
}
}
在我的XHTML文件中,我浏览了ArrayList结果的每个条目。
看起来像这样:
<ui:repeat var="res" value="#{PropertySearchBean.results}">
<p>#{res.propertyID}</p>
<p>#{res.propertyName}</p>
</ui:repeat>
我不知道如何初始化ArrayList,因为首先要做的是搜索本身,用户输入。
我感谢任何帮助!
答案 0 :(得分:0)
您已从示例中删除了getter和setter,以提高可读性。我将在此提供一个实现,以确保达成共识(特别是关于领先的下划线)。
public String getPlace() {
return _place;
}
public void setPlace(String place) {
this._place = place;
}
该物业的地方&#39;可以使用绑定值#{propertySearchBean.place}
(见下文)在您的视图中访问。
您的代码用于执行搜索。因此,您必须将用户输入从XHTML文件(视图)传输到托管bean。为此,您需要在视图中添加表单。每个搜索查询参数都使用特定的值绑定绑定到您的bean。此外,表单包含<h:commandButton>
标记,最终触发结果列表的初始化。
<h:form>
<h:outputLabel for="place" value="Place:" />
<h:inputText id="place" value="#{propertySearchBean.place}" />
<!-- Additional fields -->
<h:commandButton action="#{propertySearchBean.initializeSearchResults}"
value="Search"/>
</h:form>
注意:您已在示例
中使用了以下代码<ui:repeat var="res" value="#{PropertySearchBean.results}">
确保bean名称的第一个字母是小写的(propertySearchBean
而不是PropertySearchBean
)。所以这需要更新到
<ui:repeat var="res" value="#{propertySearchBean.results}">