我正在开发一个大型 JSF 项目,但注意到我的 session bean 都没有保留其值。为了尝试找到我的错误,我通过简单的注入(inject)创建了一个测试项目,但是我仍然发现 session 作用域 bean 没有保留其值。
我已经通过 stackoverflow.com 进行了搜索(并在 Google 上花了几个小时)寻找答案,但找不到答案。如果有任何帮助,我将非常感激。
我正在使用 JSF 2.2、Netbeans 7.3.1 和 Glassfish Server 4.0
我的简单测试项目的代码如下。
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
index.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://xmlns.jcp.org/jsf/html">
<h:head>
<title>Title</title>
</h:head>
<h:body>
<h:form>
<h:inputText value="#{bean1.title}" />
<h:commandButton action="#{bean2.test()}" />
</h:form>
</h:body>
</html>
Bean1.java
package beans;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
@Named(value = "bean1")
@SessionScoped
public class Bean1 implements Serializable {
public Bean1() {
}
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Bean2.java
package beans;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
@Named(value = "bean2")
@RequestScoped
public class Bean2 {
public Bean2() {
}
@Inject
Bean1 b1;
public String test()
{
System.out.println(b1.getTitle());
return null;
}
}
最佳答案
如果我不得不猜测,您的 CDI 1.0 beans.xml 会在应用程序服务器中造成困惑。尝试升级到 CDI 1.1 beans.xml
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
关于java - CDI Bean 不保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22286472/