HTTP 状态 500 - java.lang.ExceptionInInitializerError --> Java Restful Web 服务

Posted

技术标签:

【中文标题】HTTP 状态 500 - java.lang.ExceptionInInitializerError --> Java Restful Web 服务【英文标题】:HTTP Status 500 - java.lang.ExceptionInInitializerError --> Java Restful Web service 【发布时间】:2017-08-03 22:05:21 【问题描述】:

我正在创建一个连接到 mysql 数据库的 Web 服务。 下面是我使用 Maven、Hibernate、MySQL 工作台编写的代码。 错误在最后,我猜这个错误一定是 HibernateUtil 或 PersonDao 但我不确定。

POM Dependencies



<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.CRUD</groupId>
<artifactId>DB_Services</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>DB_Services</name>

<properties>
    <endorsed.dir>$project.build.directory/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>


<!--Repositories (Added) Start-->
<repositories>
    <repository>
        <id>org.jboss.resteasy</id>
        <url>http//repository.jboss.org/maven2/</url>
    </repository>
</repositories>
<!--Repositories (Added) End-->


<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>6.0</version>
        <scope>provided</scope>
    </dependency>

    <!--dependency (Added) Start-->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>2.3.6.Final</version>  <!--   3.1.1.Final-->
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>2.3.6.Final</version> <!--   3.1.1.Final-->
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jettison-provider</artifactId>
        <version>2.3.6.Final</version> <!--  3.1.1.Final-->
    </dependency>

    <!--Database and hibernate-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.25</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.2.2.Final</version>
    </dependency>
    <!--dependency (Added) End--> 
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArguments>
                    <endorseddirs>$endorsed.dir</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>$endorsed.dir</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>6.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

</project>



Deployment Descriptor 

<web-app 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-app_3_0.xsd"
     version="3.0">
<display-name> DB_Services</display-name>
<listener>
    <listener-    class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener- class>
</listener>
<servlet>
    <servlet-name>Resteasy</servlet-name>
    <servlet- class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Resteasy</servlet-name>
    <url-pattern>/*</url-pattern>

</servlet-mapping>

<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
</context-param>

<context-param>
    <param-name>resteasy.servlet.mapping.prefix</param-name>
    <param-value>/</param-value>
</context-param>
</web-app>


Person class
Package:com.crud.db_services.model

package com.crud.db_services.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@Entity
@Table(name = "person")
@XmlRootElement(name = "person") 
@XmlType(propOrder = "id", "fullName", "age") 
public class Person 

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name = "id") 
private int id;
@Column(name = "fullName") 
private String fullName;
@Column(name = "age") 
private int age;

@XmlElement 
public int getId() 
    return id;


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


@XmlElement 
public String getFullName() 
    return fullName;


public void setFullName(String fullName) 
    this.fullName = fullName;


@XmlElement 
public int getAge() 
    return age;


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




Service class
Package:com.crud.event_planner.services



package com.crud.event_planner.services;

import com.crud.event_planner.dao.PersonDao;
import com.crud.event_planner.model.Person;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("service") 
public class Service 

private PersonDao personDao = new PersonDao();


@GET 
@Path("/getPersonByIdXML/id") 

@Produces(MediaType.APPLICATION_XML)
public Person getPersonByIdXML(@PathParam("id") int id)  
    return personDao.getPersonById(id);



@GET 
@Path("/getPersonByIdJSON/id") 

@Produces(MediaType.APPLICATION_JSON) 
public Person getPersonByIdJSON(@PathParam("id") int id)  
    return personDao.getPersonById(id);



@GET 
@Path("/getAllPersonInXML") 

@Produces(MediaType.APPLICATION_XML)
public List<Person> getAllPersonInXML() 
    return personDao.getAllPerson();



Hibernate Configuration
Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-4.0.dtd">

<hibernate-configuration>
<session-factory>
    <!--Database Connection Settings-->
    <property  name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <!--database name -->
    <property  name="hibernate.connection.url">jdbc:mysql://localhost:3306/event_planner</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>

    <!--SQL Dialect-->
    <property           name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
    <!--Write all executed SQL statements to stdout-->
    <property name="show_sql">true</property> 

    <!--below need to change, check Source Packages and inside folders -->
    <!-- Name of the entity classes -->
    <mapping class="com.crud.db_services.model.Person"></mapping>

</session-factory>
</hibernate-configuration>


Hibernate Utility Class
 A class which help us read our configuration file
Package: com.crud.db_services.util


package com.crud.db_services.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtil 

private static final SessionFactory sessionFactory;

static 
    try 
        // Create the SessionFactory from standard (hibernate.cfg.xml) 
        // config file.
        sessionFactory = new     Configuration().configure().buildSessionFactory();
     catch (Throwable ex) 
        // Log the exception. 
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    


public static SessionFactory getSessionFactory() 
    return sessionFactory;




Data Access Object (DAO)

package com.crud.db_services.dao;


 import com.crud.db_services.model.Person;
 import com.crud.db_services.util.HibernateUtil;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;

public class PersonDao 
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

public Person getPersonById(int id) 
    Person person = null;
    Session session = null;
    try 
        session = sessionFactory.openSession();
        session.beginTransaction();
        person = (Person) session.createQuery("from Person p where p.id =  :ID").setParameter("ID", id).uniqueResult();
        session.getTransaction().commit();
     catch (Exception ex) 
        if (session != null) 
            session.getTransaction().rollback();
        
     finally 
        if (session != null) 
            session.close();
        
    
    return person;




ERROR


HTTP Status 500 - java.lang.ExceptionInInitializerError

type Exception report

 message java.lang.ExceptionInInitializerError

description The server encountered an internal error that prevented it from fulfilling this request.

 exception

org.jboss.resteasy.spi.UnhandledException:     java.lang.ExceptionInInitializerError
org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(Syn    chronousDispatcher.java:365)
     org.jboss.resteasy.core.SynchronousDispatcher.handleException(SynchronousDispatcher.java:233)
org.jboss.resteasy.core.SynchronousDispatcher.handleInvokerException(SynchronousDispatcher.java:209)
org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:557)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126)
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service    (ServletContainerDispatcher.java:208)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.ExceptionInInitializerError
com.crud.db_services.util.HibernateUtil.<clinit>(HibernateUtil.java:25)
com.crud.db_services.dao.PersonDao.<init>(PersonDao.java:13)
com.crud.db_services.services.Service.<init>(Service.java:28)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:422)
org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:82)
org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory.createResource(POJOResourceFactory.java:43)
org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:215)
org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126)
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.hibernate.HibernateException: Could not parse configuration:    /hibernate.cfg.xml
org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2075)
org.hibernate.cfg.Configuration.configure(Configuration.java:1987)
org.hibernate.cfg.Configuration.configure(Configuration.java:1966)
com.crud.db_services.util.HibernateUtil.<clinit>(HibernateUtil.java:21)
com.crud.db_services.dao.PersonDao.<init>(PersonDao.java:13)
com.crud.db_services.services.Service.<init>(Service.java:28)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:422)
org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:82)
org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory.createResource(POJOResourceFactory.java:43)
org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:215)
org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126)
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.dom4j.DocumentException: http://hibernate.org/dtd/hibernate-configuration-4.0.dtd Nested exception: http://hibernate.org/dtd/hibernate-configuration-4.0.dtd
org.dom4j.io.SAXReader.read(SAXReader.java:484)
org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2067)
org.hibernate.cfg.Configuration.configure(Configuration.java:1987)
org.hibernate.cfg.Configuration.configure(Configuration.java:1966)
com.crud.db_services.util.HibernateUtil.<clinit>(HibernateUtil.java:21)
com.crud.db_services.dao.PersonDao.<init>(PersonDao.java:13)
com.crud.db_services.services.Service.<init>(Service.java:28)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:422)
org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:82)
org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory.createResource(POJOResourceFactory.java:43)
org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:215)
org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:542)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:524)
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:126)
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

 note The full stack trace of the root cause is available in the Apache      Tomcat/7.0.75 logs.
Apache Tomcat/7.0.75

【问题讨论】:

【参考方案1】:

读取hibernate配置文件时出错:

org.hibernate.HibernateException: Could not parse configuration:    /hibernate.cfg.xml

问题在于hibernate.cfg.xml 文件,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-4.0.dtd">

用下面的代码替换上面的行:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">

【讨论】:

以上是关于HTTP 状态 500 - java.lang.ExceptionInInitializerError --> Java Restful Web 服务的主要内容,如果未能解决你的问题,请参考以下文章

HTTP 状态 500 - 请求处理失败

验证 HTTP 200 和 500 状态码的 Alamofire 响应

HTTP 状态 500 - 意外令牌:,靠近第 1 行,第 129 列

http statusCode 500状态码

http statusCode 500状态码

HTTP状态500错误实例化servlet类[重复]