JSF ViewScope beans哈希代码实现不正确



我正在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 "";
}
}

如果我根据字符串源代码多次点击命令按钮,它应该会写

class name+hashCode

但它写的东西类似于下面的

de.controller.Other@118ea91
de.controller.Other@1e8f930
de.controller.Other@1a38f3c

因此,每次我们单击都会有一个不同的视图范围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实例化上调用,但事实并非如此,所以我仍然不明白这个对象怎么会被创建好几次?

从操作方法返回非null时,将创建一个新视图。

如果要保持当前视图的活动状态,只需从action方法返回nullvoid即可。

例如

public void doSome() {
System.out.println(this);
}

另请参阅:

  • 如何选择正确的bean范围

也就是说,你认为这是一个问题的结论是正确的,但你基于你的结论的理由,"错误的哈希代码实现">,没有完全的意义。每次都只是物理上不同的bean实例。在类中添加一个默认构造函数,在其上放置一个断点,您将看到每次从操作方法返回后都会调用它,从而创建一个全新的实例。

最新更新