Java bean在同一个jsp中有多个实例

时间:2012-04-29 17:36:21

标签: java jsp jsf-2

我有一个类counterBean,我希望在我的jsp中实例化两个counterBean实例(对于两个单独的计数器)。我该怎么做?

编辑 - 添加了代码

package beans;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="CounterBean")
@SessionScoped
public class CounterBean implements Serializable
{
    private static final long serialVersionUID = 1L;
    private static int hitCount;

    public CounterBean() 
    {
        CounterBean.hitCount = 0;
    }

    public static int getCounter() 
    {
        hitCount++;
        return hitCount;
    }

    public static void setCounter(int hitCount) 
    {
        CounterBean.hitCount = hitCount;
    }

    public static int getValue() 
    {
        return hitCount;
    }
}

3 个答案:

答案 0 :(得分:1)

最好不要直接在JSP代码中创建对象。因为JSP应该只是查看。在JSP页面中使用scriptlet并不是一种好习惯。 最好使用<jsp:useBean>标记:

<jsp:useBean id="firstCounterId' class="yourpackagename.CounterBean" />
<jsp:useBean id="secondCounterId' class="yourpackagename.CounterBean" />

要更改特定计数器的值,请应用标记<jsp:set Property>

<jsp:setProperty name="firstCounterId" property="myNumber" value="123"/>

但我认为通过使用标记<c:set><c:out>

可以解决从JSP中更改和使用bean的几乎所有问题。

答案 1 :(得分:0)

按照您通常习惯的方式创建计数器bean:

@Named(value="counterBean")
@SessionScoped
public class CounterBeanClass implements Serializable {

    private int counter = 0;

    public CounterBeanClass() {
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    public String addCounterValue() {
        this.counter++;
        return "";
    }
}

然后,在faces-config.xml文件中创建或添加新的托管bean

<managed-bean>
    <managed-bean-name>anotherCounterBean</managed-bean-name>
    <managed-bean-class>my.backingbean.CounterBeanClass</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

现在您可以将两个计数器称为分离的bean。

<h:form>
    <h:panelGrid columns="2">
        <h:outputText value="Counter 1" />
        <h:outputText value="#{counterBean.counter}" />
        <h:outputText value="Counter 2" />
        <h:outputText value="#{anotherCounterBean.counter}" />
        <h:commandButton value="Add Counter 1"
            action="#{counterBean.addCounterValue}" />
        <h:commandButton value="Add Counter 2"
            action="#{anotherCounterBean.addCounterValue}" />
    </h:panelGrid>
</h:form>

答案 2 :(得分:-1)

怎么样

CounterBean cb1 = new CounterBean();
CounterBean cb2 = new CounterBean();