首页 文章

Getter 在 JSF 中返回 Null,但 Setter 显示了值

提问于
浏览
0

我继续在 StudentBean 上的 getter 方法中获取 null,但在 LoginBean 上不是。有人会看到他们是否可以帮助我吗?

--------------------code-----------------

---StudentBean---

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);
    }   

}

---LoginProg---

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>

--------------------end 代码-----------------

我使用 SysOuts 打印检查点,试图观察活动从我的 JSF 页面到豆类的工作 debug/tracer

当我的 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

1 回答

  • 0

    您可以“手动”创建 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,则它创建一个实例并放入会话范围上下文)。

相关问题