0

Topic
The topic of this question is: JSF_navigation and database connection
Hello and Thank you in advance for any assistance.


System info:

Netbeans6.7.1,jsf1.2,two MySQL databases.(one for login one for searches)


The purpose of this post is:

Try to get the login jsp to switch to the next page and understand how to connect to the database to simulate a login .



The functionality of this code is:

I have two databases one for login and one for finding contents of several music book records. Searches performed via artist or song. The first order of operation is Login.jsp which submits the user name “uid” (user Name and password are the same) and are validated simple uid>8 characters. Upon login the login.jsf page should navigate to the success.jsp or fail.jsp via faces-config file . The login.jsp submits to the controller, the controller calls the model to validate and connect to the splashbookdb_user database. that’s all for now.
(the design of the code does absolutely nothing now. I just can’t get the connection worked out.)

(jsf pages,SplashbookController.java,SplashbookModel.java and Content.java (entity).

I will be updating the splashbook project periodically at:
http://cid-b5cb457363230793.skydrive.live.com/self.aspx/.Public/splashbookdb^_and^_netbeans^_project%20-%20Copy.zip

The errors related to this code are:



Error description: Mozilla firefox

------------

HTTP Status 500 -

type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: #{SplashbookController.ValidateUser}: java.lang.NullPointerException

root cause

javax.faces.FacesException: #{SplashbookController.ValidateUser}: java.lang.NullPointerException

root cause

javax.faces.el.EvaluationException: java.lang.NullPointerException

root cause

java.lang.NullPointerException

note The full stack traces of the exception and its root causes are available in the Sun GlassFish Enterprise Server v2.1 logs.


Code description:faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="1.2" 
    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/web-facesconfig_1_2.xsd">
    <managed-bean>
        <managed-bean-name>SplashbookController</managed-bean-name>
        <managed-bean-class>controllers.SplashbookController</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/login.jsp</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/loginSuccess.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>fail</from-outcome>
            <to-view-id>/loginFail.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>

</faces-config>


Code description:login.jsp

<%-- 
    Document   : login
    Created on : Oct 7, 2009, 8:45:20 PM
    Author     : depot
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<f:view>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
            <title>splashbook Login Page</title>
            <link rel="stylesheet" type="text/css" href="css/style1.css" />
        </head>
        <body>
            <h1><h:outputText value="username=student1"/></h1>
            <h1><h:outputText value="password= student1"/></h1>

            <h:form id="LoginApplication">
                <h:panelGrid id="loginPanel" columns="2">
                    <h:outputText value="user ID"/>
                    <h:inputText id="loginId" value="#{SplashbookController.uid}"/>
                    <h:outputText value="Password"/>
                    <h:inputSecret id="password"  value="#{SplashbookController.password}"/>
                    <h:outputText value=""/>
                    <h:commandButton value="login" action ="#{SplashbookController.ValidateUser}"/>
                </h:panelGrid>
            </h:form>


        </body>
    </html>
</f:view>


Code description:SplashBookController.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

/**
 *
 * @author depot
 */
import classes.SplashbookModel;
import entities.Content;

import java.sql.Connection;

public class SplashbookController {

    public SplashbookModel splashbookModel;
    public String uid;
    public String password;
    public String database;
   
    public int uidLength = 8;
    public String loginResult;
    public Connection conn;

    /** Creates a new instance of SplashbookController */
    public SplashbookController() {
    }

    public String ValidateUser() throws Exception {

        if (uid.length() >= 8) {
                database="splashbookdb_user";
                System.out.println("database name-------------->"+database+"<-------------------");
                splashbookModel.connectToUserDB(database);
                if(splashbookModel.getConn().equals(null)){
                    loginResult="fail";
                }else{
                    loginResult="success";
                }
        }
        System.out.println("loginResult-------------->"+loginResult+"<-------------------");
           return loginResult;
    }
    public String getLoginResult() {
        return loginResult;
    }

    public void setLoginResult(String loginResult) {
        this.loginResult = loginResult;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public int getUidLength() {
        return uidLength;
    }

    public void setUidLength(int uidLength) {
        this.uidLength = uidLength;
    }

   
}


Code description:SplashbookModel.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package classes;

/**
 *
 * @author depot
 */
import controllers.SplashbookController;
import entities.Content;
import java.sql.Connection;
import java.sql.DriverManager;
public class SplashbookModel {

        
        public Connection conn=null;
        public StringBuffer buff=null;
        public String host="localhost";
        public String database;
        public String dbUserName="root";
        public String dbPassword="ceyesuma";
       
   
public SplashbookModel(){

}


   public Connection connectToUserDB(String database)throws Exception {
       System.out.println("splashbookModel.connectToUserDB()-------------->"+database+"<-------------------");
        try {
            buff = new StringBuffer();
            buff.append("jdbc:mysql://");
            buff.append(host);
            buff.append("/");
            buff.append(database);
            buff.append("?user=");
            buff.append(dbUserName);
            buff.append("&password=");
            buff.append(dbPassword);
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(buff.toString());
            System.out.println("Connection URL: ----------------->" + buff+"<-----------------");
        } catch (Exception ex) {
            throw new Exception("An error occurred while attempting to connect to[" + buff + "]");

        }
        return conn;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public String getDbPassword() {
        return dbPassword;
    }

    public void setDbPassword(String dbPassword) {
        this.dbPassword = dbPassword;
    }

    public String getDbUserName() {
        return dbUserName;
    }

    public void setDbUserName(String dbUserName) {
        this.dbUserName = dbUserName;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public StringBuffer getBuff() {
        return buff;
    }

    public void setBuff(StringBuffer buff) {
        this.buff = buff;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }
   
 

}


The Entities from db’s related to this code are:

User.java used to log in.
Usergroup.java used to log in and specify permissions.
Content.java used for searching.


Code description:Content

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 *
 * @author depot
 */
@Entity
@Table(name = "content")
@NamedQueries({@NamedQuery(name = "Content.findAll", query = "SELECT c FROM Content c"), @NamedQuery(name = "Content.findById", query = "SELECT c FROM Content c WHERE c.id = :id"), @NamedQuery(name = "Content.findByPublisherCode", query = "SELECT c FROM Content c WHERE c.publisherCode = :publisherCode"), @NamedQuery(name = "Content.findByBookIsbn", query = "SELECT c FROM Content c WHERE c.bookIsbn = :bookIsbn"), @NamedQuery(name = "Content.findByBookTitle", query = "SELECT c FROM Content c WHERE c.bookTitle = :bookTitle"), @NamedQuery(name = "Content.findByArtist", query = "SELECT c FROM Content c WHERE c.artist = :artist"), @NamedQuery(name = "Content.findBySong", query = "SELECT c FROM Content c WHERE c.song = :song"), @NamedQuery(name = "Content.findByPageNum", query = "SELECT c FROM Content c WHERE c.pageNum = :pageNum")})
public class Content implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "publisher_code")
    private String publisherCode;
    @Column(name = "book_isbn")
    private String bookIsbn;
    @Column(name = "book_title")
    private String bookTitle;
    @Column(name = "artist")
    private String artist;
    @Column(name = "song")
    private String song;
    @Column(name = "page_num")
    private Integer pageNum;

    public Content() {
    }

    public Content(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getPublisherCode() {
        return publisherCode;
    }

    public void setPublisherCode(String publisherCode) {
        this.publisherCode = publisherCode;
    }

    public String getBookIsbn() {
        return bookIsbn;
    }

    public void setBookIsbn(String bookIsbn) {
        this.bookIsbn = bookIsbn;
    }

    public String getBookTitle() {
        return bookTitle;
    }

    public void setBookTitle(String bookTitle) {
        this.bookTitle = bookTitle;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getSong() {
        return song;
    }

    public void setSong(String song) {
        this.song = song;
    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Content)) {
            return false;
        }
        Content other = (Content) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entities.Content[id=" + id + "]";
    }

}


Code description:User.java(entity)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 *
 * @author depot
 */
@Entity
@Table(name = "user")
@NamedQueries({@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findByUid", query = "SELECT u FROM User u WHERE u.uid = :uid"), @NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"), @NamedQuery(name = "User.findByFirstName", query = "SELECT u FROM User u WHERE u.firstName = :firstName"), @NamedQuery(name = "User.findByLastName", query = "SELECT u FROM User u WHERE u.lastName = :lastName"), @NamedQuery(name = "User.findByAddress1", query = "SELECT u FROM User u WHERE u.address1 = :address1"), @NamedQuery(name = "User.findByAddress2", query = "SELECT u FROM User u WHERE u.address2 = :address2"), @NamedQuery(name = "User.findByCity", query = "SELECT u FROM User u WHERE u.city = :city"), @NamedQuery(name = "User.findByPostCode", query = "SELECT u FROM User u WHERE u.postCode = :postCode"), @NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email"), @NamedQuery(name = "User.findByPhone", query = "SELECT u FROM User u WHERE u.phone = :phone"), @NamedQuery(name = "User.findByUserGroup", query = "SELECT u FROM User u WHERE u.userGroup = :userGroup")})
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "uid")
    private String uid;
    @Basic(optional = false)
    @Column(name = "password")
    private String password;
    @Basic(optional = false)
    @Column(name = "firstName")
    private String firstName;
    @Basic(optional = false)
    @Column(name = "lastName")
    private String lastName;
    @Basic(optional = false)
    @Column(name = "address1")
    private String address1;
    @Basic(optional = false)
    @Column(name = "address2")
    private String address2;
    @Basic(optional = false)
    @Column(name = "city")
    private String city;
    @Basic(optional = false)
    @Column(name = "postCode")
    private String postCode;
    @Column(name = "email")
    private String email;
    @Column(name = "phone")
    private Integer phone;
    @Basic(optional = false)
    @Column(name = "userGroup")
    private String userGroup;
    @ManyToMany(mappedBy = "userCollection")
    private Collection<Usergroup> usergroupCollection;

    public User() {
    }

    public User(String uid) {
        this.uid = uid;
    }

    public User(String uid, String password, String firstName, String lastName, String address1, String address2, String city, String postCode, String userGroup) {
        this.uid = uid;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address1 = address1;
        this.address2 = address2;
        this.city = city;
        this.postCode = postCode;
        this.userGroup = userGroup;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getPostCode() {
        return postCode;
    }

    public void setPostCode(String postCode) {
        this.postCode = postCode;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getPhone() {
        return phone;
    }

    public void setPhone(Integer phone) {
        this.phone = phone;
    }

    public String getUserGroup() {
        return userGroup;
    }

    public void setUserGroup(String userGroup) {
        this.userGroup = userGroup;
    }

    public Collection<Usergroup> getUsergroupCollection() {
        return usergroupCollection;
    }

    public void setUsergroupCollection(Collection<Usergroup> usergroupCollection) {
        this.usergroupCollection = usergroupCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (uid != null ? uid.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof User)) {
            return false;
        }
        User other = (User) object;
        if ((this.uid == null && other.uid != null) || (this.uid != null && !this.uid.equals(other.uid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entities.User[uid=" + uid + "]";
    }

}


Code description:Usergroup.java(Entity class)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 *
 * @author depot
 */
@Entity
@Table(name = "usergroup")
@NamedQueries({@NamedQuery(name = "Usergroup.findAll", query = "SELECT u FROM Usergroup u"), @NamedQuery(name = "Usergroup.findByGroupid", query = "SELECT u FROM Usergroup u WHERE u.groupid = :groupid"), @NamedQuery(name = "Usergroup.findByGroupName", query = "SELECT u FROM Usergroup u WHERE u.groupName = :groupName")})
public class Usergroup implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "groupid")
    private String groupid;
    @Basic(optional = false)
    @Column(name = "groupName")
    private String groupName;
    @JoinTable(name = "usergroup_mapping", joinColumns = {@JoinColumn(name = "groupid", referencedColumnName = "groupid")}, inverseJoinColumns = {@JoinColumn(name = "uid", referencedColumnName = "uid")})
    @ManyToMany
    private Collection<User> userCollection;

    public Usergroup() {
    }

    public Usergroup(String groupid) {
        this.groupid = groupid;
    }

    public Usergroup(String groupid, String groupName) {
        this.groupid = groupid;
        this.groupName = groupName;
    }

    public String getGroupid() {
        return groupid;
    }

    public void setGroupid(String groupid) {
        this.groupid = groupid;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public Collection<User> getUserCollection() {
        return userCollection;
    }

    public void setUserCollection(Collection<User> userCollection) {
        this.userCollection = userCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (groupid != null ? groupid.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Usergroup)) {
            return false;
        }
        Usergroup other = (Usergroup) object;
        if ((this.groupid == null && other.groupid != null) || (this.groupid != null && !this.groupid.equals(other.groupid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entities.Usergroup[groupid=" + groupid + "]";
    }

}


Thanks again.
-ceyesuma



Note:

________________________________________________________________________

Code description:

1
Contributor
2
Replies
3
Views
7 Years
Discussion Span
Last Post by ceyesuma
0

I added a servlet to this project to remove the database metadata and set param's . so I this means I have to have a method to get the database connection info from the web.xml

but the faces-config.xml is what is controlling the page navigation?
it is a managed bean. so can I use both of these xml together?

0

Hello.
I am termnating this post
Due to the fact I am in way over my head. I have finally found some good study material.
I have summerized this new material in an excel file (a book from my study guide) if any one is interested in studing some jsf.
Any feed back on my study guide would be appreciated I am trying to polish it in order to build my own study guide some day.
I could use some help with that one.

Thanks
ceyesuma

jsf study guide page and or the entire study guide project
http://cid-b5cb457363230793.skydrive.live.com/browse.aspx/.Public

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.