【问题标题】:Getter returning Null in JSF but Setter Show the ValueGetter 在 JSF 中返回 Null 但 Setter 显示值
【发布时间】:2017-09-17 20:12:38
【问题描述】:

我在 StudentBean 上的 getter 方法中不断得到 null,但在 LoginBean 上却没有。有人能帮我看看吗?

--------------------------------代码-----------------

---学生豆---

package edu.jhu.jee;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.faces.bean.ManagedBean;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

import edu.jhu.jee.LoginProg;
import edu.jhu.jee.SessionUtils;


@ManagedBean (name="studentBean")
@SessionScoped 

public class StudentBean implements Serializable {

    private String firstName;
    private String lastName;

    public String getFirstName() {
        System.out.println("StudentBean getFirstName!!!!!!!!!!!!!!!!" +firstName);
        return this.firstName;      
    }   

    public String getLastName() {
        System.out.println("StudentBean getLastName!!!!!!!!!!!!!!!!"+lastName);
        return this.lastName;       
    }

    public void setFirstName(String first_Name) {
        this.firstName = first_Name;
        System.out.println("StudentBean setFirstName!!!!!!!!!!!!!!  "+firstName);       
    }


    public void setLastName(String last_Name) {
        this.lastName = last_Name;
        System.out.println("StudentBean setLastName!!!!!!!!!!!! "+lastName);
    }   

}

---登录程序---

package edu.jhu.jee; 

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.Serializable;


public class LoginProg {

    public static String authenticate(String userid, String password) {



            String sqlStmt = null;

            Context ctx = null;
            Hashtable ht = new Hashtable();
            ht.put(Context.INITIAL_CONTEXT_FACTORY,
             "weblogic.jndi.WLInitialContextFactory");
            ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
            String st = null;

            sqlStmt = ("SELECT * FROM APP.STUDENT WHERE USERID='"+userid+"'AND PASSWORD='"+password+"'");
            try {
            ctx = new InitialContext(ht);

            javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup ("jhuDataSource");
            conn = ds.getConnection();
            stmt = conn.createStatement();
            //  takes SQL statements from Login and Register servlets:          
                        rs =stmt.executeQuery(sqlStmt);


                        // Reads data objects in database Going Forward
                            while (rs.next()){
                                //Student object to fill with Student data
                                String first_name   = rs.getObject(3).toString();
                                String last_name    = rs.getObject(4).toString();
                                st = first_name + " " + last_name;
                                System.out.println(st);

                                StudentBean studentBean = new StudentBean();
                                studentBean.setFirstName(first_name);
                                studentBean.setLastName(last_name);


                            } 

                        if (st == null){ // check if user id exist at least
                        sqlStmt = ("SELECT * FROM APP.STUDENT WHERE USERID='"+userid+"'");
                        rs =stmt.executeQuery(sqlStmt);
                            while (rs.next()){
                                //Student object to fill with Student data
                                String user_id  = rs.getObject(1).toString();
                                st = user_id;
                                System.out.println("Password incorrect for "+st);
                            }
                        } else {} // Do nothing



            stmt.close();
            conn.close();

      }catch(Exception e) {e.printStackTrace();}

        finally {    
          try { 
            ctx.close(); 
          } catch (Exception e) {System.out.println(e);}
          try { 
            if (rs != null) rs.close(); 
          } catch (Exception e) {System.out.println(e);}
          try { 
            if (stmt != null) stmt.close(); 
          } catch (Exception e) {System.out.println(e);}
          try { 
            if (conn != null) conn.close(); 
          } catch (Exception e) {System.out.println(e);}
        }               

    return st;

    } 
}

-----welcome.xhtml-----

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" >



<h:head>
<title>Welcome</title>
<style>body {background-color: rgb(30, 145, 255);}</style>
</h:head>

<h:body>
    <h:form>
    <h2>Hello, #{studentBean.firstName} #{studentBean.lastName}!</h2>
    <h2>Hello, #{loginBean.userid} #{loginBean.password}!</h2>
    <h:panelGrid columns="1" border="0">
    <h:panelGroup>
        <h:outputText value="Select your next action: " />
            <h:selectOneRadio value = "#{userData.data}"> 
            <f:selectItem itemValue = "courseRegister" itemLabel = "Register for the course" /> 
            <f:selectItem itemValue = "logout" itemLabel = "Logout" />
        </h:selectOneRadio>
    </h:panelGroup>
    <h:panelGroup>
        <h:commandButton id="submit" value="Submit" action="NextAction">
        </h:commandButton>
    </h:panelGroup>
    </h:panelGrid>

    </h:form>
</h:body>
</html>

--------------------代码结束-----

我使用 SysOuts 打印检查点以尝试观察活动 从我的 JSF 页面到 bean 类型的工作调试/跟踪器

这个输出是在我的 login.xhtml 提交时生成的 并且 LoginBean 加载了属性:

LoginBean setUserid!!!!!!!!!!!!!!jd001_id

LoginBean setPassword!!!!!!!!!!!!jd001_pw

我的验证程序的数据库查询结果

John_001 Doe_001

通过从验证程序调用 setter 将值发送到 StudentBean:

StudentBean setFirstName!!!!!!!!!!!!!!  John_001

StudentBean setLastName!!!!!!!!!!!! Doe_001

欢迎尝试从 StudentBean 检索名称的 JSF 页面:

StudentBean getFirstName!!!!!!!!!!!!!!!!null

StudentBean getLastName!!!!!!!!!!!!!!!!null

在欢迎页面中从登录 bean 进行额外检索 显示从 LoginBean 成功检索属性:

LoginBean getUserid!!!!!!!!!!!!jd001_id

LoginBean getPassword!!!!!!!jd001_pw

【问题讨论】:

  • 你能把验证程序代码贴在你使用setter的地方吗?
  • 请插入 login.xhtml 和 welcome.xhtml facelets
  • minimal reproducible example 请,您的调试输出很难阅读
  • 您好 OTM 和 Bitman,我已经添加了身份验证程序和欢迎代码。
  • 嗨 Kukeltje - 为了清晰起见,我已经重新组织了系统输出。

标签: jsf


【解决方案1】:

您“手动”创建一个 StudentBean。这是错误的。托管 bean 的意思是:容器在作用域上下文创建时创建它们,上下文将释放它们。

使用@Named 而不是'@ManagedBean'(很快就会被弃用)并以这种方式访问​​LoginProg.authenticate() 中的StudentBean 实例:

HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession( true );
StudentBean studentBean = (StudentBean) session.getAttribute("studentBean");
if ( studentBean == null )
{
  studentBean = new StudentBean();
  session.setAttribute( "studentBean", studentBean );
}
studentBean.setFirstName( first_name );
...

容器应该使用 HttpSession 实例创建 studentBean,但我肯定检查了 bean 的存在(如果它为 null,它会创建一个实例并放入会话范围上下文中)。

【讨论】:

  • 嗨,Bitman,我试过了,结果出现编译错误:对象无法转换为 StudentBean。我正在使用会话实用程序,不确定是否需要在那里做任何事情。
  • 好的,我想我可能已经通过避免使用 StudentBean 来解决这个问题。我使用 LoginProg 返回元素将结果返回给 LoginBean,从而使其可用于欢迎页面。感谢大家的意见。您的 cmets 和回复帮助我解决了这个问题。谢谢。
  • 好的。我修改了答案并将 Object 转换为 StudentBean。
  • 如果您接受一个可行的解决方案,在此表达感谢的最佳方式(不管您是否改变了主意 :))
  • 感谢比特曼。该解决方案确实将属性传递给会话,因为由于实例不匹配,getter 无法工作。 session.setAttribute("studentBean", studentBean);使该属性可在 jsf 页面中使用。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 2014-05-08
  • 1970-01-01
相关资源
最近更新 更多