[英]JSF Java Beans - initialize and proceed
我是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,因为首先要做的是使用用户输入进行搜索。
我感谢您提供的任何帮助!
您已从示例中删除了getter和setter,以提高可读性。 我将在此处提供一种实现方式,以确保有一个共识(尤其是关于下划线的问题)。
public String getPlace() {
return _place;
}
public void setPlace(String place) {
this._place = place;
}
通过使用值绑定#{propertySearchBean.place}
(在下文中),可以在视图中访问属性'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}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.