【发布时间】:2014-02-18 16:15:41
【问题描述】:
我正在开发一个基于 JSF 的简单应用程序,具有以下依赖项
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-impl</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>2.0.2</version>
</dependency>
并且是一个简单的页面,它支持 bean。
xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<title></title>
</head>
<body >
<h:form>
<f:view >
<h:commandButton id="otxMainPanelTextBt" value="click"
action="#{otherController.doSome}"/>
</f:view>
</h:form>
</body>
</html>
Java 代码
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "otherController")
@ViewScoped
public class Other implements Serializable {
private static final long serialVersionUID = -6493758917750576706L;
public String doSome() {
System.out.println(this);
return "";
}
}
如果我根据toString源代码多次点击commandButton应该这样写
class name+hashCode
但它会写如下内容
de.controller.Other@118ea91
de.controller.Other@1e8f930
de.controller.Other@1a38f3c
因此,每次我们单击时,viewscoped bean 都会有不同的哈希码。这是不正确的吗?我尝试过使用会话 bean,但没有发生这种情况。
编辑
我按照@BalusC的建议修改了这个类,方法如下。
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "otherController")
@ViewScoped
public class Other implements Serializable {
private static final long serialVersionUID = -6493758917750576706L;
@PostConstruct
public void init()
{
System.out.println("Post Construction");
}
public Other()
{
System.out.println("Constructor");
}
public void doSome() {
System.out.println(this);
}
}
而且我点击多次后发现了这个输出。
Constructor
Post Construction
de.controller.Other@b748dd
de.controller.Other@1620dca
de.controller.Other@116358
de.controller.Other@73cb2d
de.controller.Other@1cc3ba0
因此,构造函数和 PostConstructor 方法仅被调用一次,尽管如此,该对象在每次调用中仍然具有不同的哈希码。这很奇怪,因为应该在托管 bean 实例化上调用不带参数的构造函数,但事实并非如此,所以我仍然不明白如何多次创建对象?
【问题讨论】:
-
使用更新版本的 myfaces 核心。最新版本(2.0.20、2.1.14)被认为是最稳定的。这看起来像是一个在史前时代就解决了的古老问题。
标签: jsf-2