JPA与Tomcat的集成给出了空指针异常

时间:2017-03-05 13:15:41

标签: java maven tomcat jsf jpa

我已经在J2SE中使用Maven成功实现了JPA。现在,我正在尝试使用JSF在J2EE中使用它,但我得到空指针异常错误。

我的项目结构是: Project Structure

POM文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>lotus</groupId>
    <artifactId>fsoftAssisgnment</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>fsoftAssisgnment Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <!-- <scope>provided</scope> -->
        </dependency>

        <!-- Servlet Setup -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.13</version>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.13</version>
        </dependency>       
    </dependencies>
    <build>
        <finalName>fsoftAssisgnment</finalName>
    </build>
</project>

Persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="JavaHelps" transaction-type="RESOURCE_LOCAL">
        <!-- Persistence provider -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <!-- Entity classes -->
        <class>lotus.fsoftAssignment.entities.Student</class>
        <properties>
            <!-- The JDBC driver of your database -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <!-- The JDBC URL to the database instance -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/testprojectdb" />
            <!-- The database username -->
            <property name="javax.persistence.jdbc.user" value="root" />
            <!-- The database password -->
            <property name="javax.persistence.jdbc.password" value="" />
        </properties>
    </persistence-unit>
</persistence>

Student.java:

package lotus.fsoftAssignment.entities;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student implements Serializable {
    @Id
    @Column(name = "student_id", unique = true)
    private int id;

    @Column(name = "student_name", nullable = false)
    private String name;

    @Column(name = "student_age", nullable = false)
    private int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return id + "\t" + name + "\t" + age;
    }
}

StudentDaoImpl.java:

package lotus.fsoftAssignment.entities;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class StudentDaoImpl {
    // Create an EntityManagerFactory when you start the application.
    private final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("JavaHelps");

    public void delete(int id) {
        // Create an EntityManager
        EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
        EntityTransaction transaction = null;

        try {
            // Get a transaction
            transaction = manager.getTransaction();
            // Begin the transaction
            transaction.begin();

            // Get the Student object
            Student stu = manager.find(Student.class, id);

            // Delete the student
            manager.remove(stu);

            // Commit the transaction
            transaction.commit();
        } catch (Exception ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the EntityManager
            manager.close();
        }
     // NEVER FORGET TO CLOSE THE ENTITY_MANAGER_FACTORY
        ENTITY_MANAGER_FACTORY.close();
    }

}

我有用于删除函数实现的Main.class,如下所示:

   public class Main {          
        private static StudentDaoImpl stuimpl = new StudentDaoImpl();
        public static void main(String[] args) {
            stuimpl.delete(20);
}
    }

到目前为止,删除功能按预期工作,没有任何问题。

现在,我尝试将它与JSF集成,这给了我java null指针异常。为此,我修改了Main类,如下所示:

@ManagedBean(name="main")
@SessionScoped
public class Main { 

    private static StudentDaoImpl stuimpl = new StudentDaoImpl();
public void delete() {
        stuimpl.delete(20);
    }

}

我的welcome.xhtml文件为:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>

<body>
    <h3>Return All Users</h3>
    <h:commandButton value="Delete" action="#{main.delete}"></h:commandButton>

</body>
</html>

web.xml文件:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>faces/welcome.xhtml</welcome-file>
    </welcome-file-list>

</web-app>

当我右键点击项目时 - >运行As-&gt;在服务器上运行 - &gt; Tomcat 7 Server-&gt;在我的本地机器上使用ecllipse运行它会给我以下错误: Error shown after running it on tomcat server. The error occurs in a dialog box.

这是控制台中显示的日志:

Mar 05, 2017 6:54:08 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:fsoftAssisgnment' did not find a matching property.
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/7.0.68
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Feb 8 2016 20:25:54 UTC
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         7.0.68.0
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 8
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            6.2
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.8.0_05\jre
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_05-b13
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\enjal\Desktop\workspace-jsf\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache\apache-tomcat-7.0.68
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\enjal\Desktop\workspace-jsf\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache\apache-tomcat-7.0.68
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\enjal\Desktop\workspace-jsf\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache\apache-tomcat-7.0.68\endorsed
Mar 05, 2017 6:54:08 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Mar 05, 2017 6:54:08 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_05\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.8.0_05/jre/bin/server;C:/Program Files/Java/jdk1.8.0_05/jre/bin;C:/Program Files/Java/jdk1.8.0_05/jre/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\MATLAB\R2011a\runtime\win64;C:\Program Files\MATLAB\R2011a\bin;C:\Program Files\Java\jdk1.8.0_05;C:\Program Files\Java\jdk1.8.0_05\bin;C:\Program Files\Java\jre8;C:\Program Files\Java\jre8\bin;C:\xampp\php;C:\ProgramData\ComposerSetup\bin;D:\maven\bin;C:\Program Files (x86)\Skype\Phone\;C:\Users\enjal\Anaconda2;C:\Users\enjal\Anaconda2\Scripts;C:\Users\enjal\Desktop;;.
Mar 05, 2017 6:54:09 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 05, 2017 6:54:09 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 05, 2017 6:54:09 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 3235 ms
Mar 05, 2017 6:54:09 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 05, 2017 6:54:09 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.68
Mar 05, 2017 6:54:13 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [2,792] milliseconds.
Mar 05, 2017 6:54:15 PM org.apache.catalina.loader.WebappClassLoaderBase validateJarFile
INFO: validateJarFile(C:\Users\enjal\Desktop\workspace-jsf\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\fsoftAssisgnment\WEB-INF\lib\javaee-api-7.0.jar) - jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class
Mar 05, 2017 6:54:19 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 05, 2017 6:54:19 PM com.sun.faces.config.ConfigureListener contextInitialized
INFO: Initializing Mojarra 2.1.13 ( 20120907-1514) for context '/fsoftAssisgnment'
Mar 05, 2017 6:54:21 PM com.sun.faces.spi.InjectionProviderFactory createInstance
INFO: JSF1048: PostConstruct/PreDestroy annotations present.  ManagedBeans methods marked with these annotations will have said annotations processed.
Mar 05, 2017 6:54:29 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 05, 2017 6:54:29 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 05, 2017 6:54:29 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 19820 ms

现在,当我点击welcome.xhtml页面中的“删除”按钮时,它不起作用。 我相信在服务器中运行它时会出现问题,因为它在Main类中的main函数内运行时工作正常。

我尝试将persistence.xml文件更改为JTA但是没有用。你能帮忙吗?

0 个答案:

没有答案