【发布时间】:2015-08-14 09:55:02
【问题描述】:
容器是 Glassfish。我在一个简单的 DAO bean 类中实现了一个@PostConstruct 生命周期事件拦截器方法,但似乎由于某种原因它根本没有拦截我的业务方法。我不会在任何地方手动实例化 bean 类。 beans.xml 发现模式是全部,由于我没有注释 DefaultUserDao bean,所以它获得了默认范围。
public class DefaultUserDao implements UserDao {
private String userName;
private String password;
Scanner users = null;
String[] userNamePasswordPairs = null;
public DefaultUserDao() {
try {
users = new Scanner(Paths.get("/home/NetBeansProjects/EJBInAction/web/users"));
}
catch (IOException ex) {
Logger.getLogger(DefaultUserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
/*The interceptor for this method is defined right below, that
interceptor method is not called at all. If I insert a
System.out.println(userNamePasswordPairs) after the split()
method below, it prints [userName:password] pair twice and there
is only one line in the text file from which the pair was read in the
form like this admin:admin. Notice that I also insert a System.out.println()
method in the interceptor method but if I remove the print()
method from this init() method, I don't see it prints anything
*/
@PostConstruct
public void init() {
while (users.hasNextLine()) {
String line = users.nextLine();
userNamePasswordPairs = line.split(":");
//If I uncomment this, I see it prints [admin:admin] pair
//twice, but when I comment it out, I don't see it prints anything
//System.out.println(Arrays.toString(userNamePasswordPairs));
userName = userNamePasswordPairs[0];
password = userNamePasswordPairs[1];
}
}
@AroundConstruct
private void printUser(InvocationContext ic) {
//If this interceptor was invoked, it should print at least "Interceptor invoked: "
//But it does not print this.
System.out.println("Interceptor invoked: " + Arrays.toString(userNamePasswordPairs));
try {
ic.proceed();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
一个收集用户名和密码的简单 JSF 页面
@Named
@RequestScoped
public class LoginBean {
private String userName;
private String password;
@Inject
private UserDao userDao;
public LoginBean() {
}
public LoginBean(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String validateUser() {
if (userDao.getUserName().equals(userName) && userDao.getPassword().equals(password)) {
}
else {
userName = "Error";
password = "Error";
}
return "confirmation.xhtml";
}
//getter and setter for userName and password
}
【问题讨论】:
-
@PostContruct 不适用于 pojo。仅在 jsf、cdi、ejb 等托管 bean 上。
-
它是一个豆子。我可以将它注入
LoginBean -
怎么样?通过xml文件?不是通过注释
-
是的。
beans.xml发现模式是全部,由于我没有注释DefaultUserDao,所以它获取默认范围 -
请在代码前将所有这些添加到问题中
标签: jsf glassfish cdi interceptor