19
Апр
2018

Java + Hibernate 5 + Servlets. При попытке обратиться к БД из сервлета, появляется ошибка

Код ошибки:

Exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause

java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
    net.chemodurov.productfromthemanufacturer.dao.HibernateUserDAOImpl.validate(HibernateUserDAOImpl.java:59)
    net.chemodurov.productfromthemanufacturer.controller.LoginServlet.doGet(LoginServlet.java:24)
    net.chemodurov.productfromthemanufacturer.controller.LoginServlet.doPost(LoginServlet.java:13)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause

java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1136)
    net.chemodurov.productfromthemanufacturer.dao.HibernateUserDAOImpl.validate(HibernateUserDAOImpl.java:59)
    net.chemodurov.productfromthemanufacturer.controller.LoginServlet.doGet(LoginServlet.java:24)
    net.chemodurov.productfromthemanufacturer.controller.LoginServlet.doPost(LoginServlet.java:13)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.

index.jsp:

<%@ page contentType="text/html;charset=UTF-8"%>
<html>
<head>
    <title>Login page</title>
</head>
<body>
        <form action="${pageContext.request.contextPath}/login"method="POST">
            <input type="text" placeholder="name" name = "name"/>
            <input type="password" placeholder="password" name="password"/>
            <button>login</button>
            <p class="message">Not registered? <a href="registration.jsp">Create an account</a></p>
        </form>
</body>
</html>

LoginServlet:

import javax.servlet.RequestDispatcher;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
}

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        UserDAO userDAO = new HibernateUserDAOImpl();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("name");
        String password = request.getParameter("password");

        if (userDAO.validate(username, password)) {
            RequestDispatcher rs = request.getRequestDispatcher("/manufacturers");
            rs.forward(request, response);
        }
        else {
            out.println("Access denied!");
            RequestDispatcher rs =     request.getRequestDispatcher("index.jsp");
            rs.include(request, response);
        }
    }
}

POJO-класс User:

import javax.persistence.*;

@Entity
@Table(name = "users")
public class User {
    private long id;
    private String name;
    private String password;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    public long getId() {
        return id;
    }

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

    @Column(name = "name")
    public String getName() {
        return name;
    }

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

    @Column(name = "password")
    public String getPassword() {
        return password;
    }

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

класс HibernateUserDAOImpl:

import org.hibernate.Session;
import org.hibernate.query.Query;

import java.util.HashSet;
import java.util.Set;

public class HibernateUserDAOImpl implements UserDAO {

    @Override
    public void add(User entity) {
        Session session = HibernateSessionFactory.getSessionFactory().openSession();
        session.save(entity);
        session.close();
    }

    @Override
    public User getById(Long id) {
        Session session = HibernateSessionFactory.getSessionFactory().openSession();
        User product = session.get(User.class, id);
        session.close();
        return product;
    }

    @Override
    public void update(User entity) {
        Session session = HibernateSessionFactory.getSessionFactory().openSession();
        session.beginTransaction();
        session.update(entity);
        session.flush();
        session.close();
    }

    @Override
    public void delete(Long id) {
        Session session = HibernateSessionFactory.getSessionFactory().openSession();
        session.beginTransaction();
        User product = session.get(User.class, id);
        session.delete(product);
        session.flush();
        session.close();
    }

    @Override
    public Set<User> getAll() {
        Set<User> products;
        Session session = HibernateSessionFactory.getSessionFactory().openSession();
        products = new HashSet<User>(session.createQuery("FROM User").list());
        session.close();
        return products;
    }

    @Override
    public boolean validate(String name, String password) {
        Session session = HibernateSessionFactory.getSessionFactory().openSession();
        Query query = session.createQuery("from User where name=:username and password=:password");
        query.setParameter("username", name);
        query.setParameter("password", password);
        boolean result = !query.list().isEmpty();
        session.close();
        return result;
    }
}

класс HibernateSessionFactory: (так корректно же создавать фабрику?)

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateSessionFactory {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder()
                        .configure()
                        .build();

                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);

                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();

                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();

            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }

    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>ProductsFromTheManufacturer</groupId>
    <artifactId>net.chemodurov. productsfromthemanufacturer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.16.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.11</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.2.11</version>
        </dependency>

        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>



    </dependencies>


    <build>
        <finalName>ProductManufacturerSystem</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8080</port>
                    <path>/</path>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

Источник: https://ru.stackoverflow.com/questions/816634/java-hibernate-5-servlets-%D0%9F%D1%80%D0%B8-%D0%BF%D0%BE%D0%BF%D1%8B%D1%82%D0%BA%D0%B5-%D0%BE%D0%B1%D1%80%D0%B0%D1%82%D0%B8%D1%82%D1%8C%D1%81%D1%8F-%D0%BA-%D0%91%D0%94-%D0%B8%D0%B7-%D1%81%D0%B5%D1%80%D0%B2%D0%BB%D0%B5%D1%82%D0%B0-%D0%BF%D0%BE%D1%8F%D0%B2%D0%BB%D1%8F%D0%B5%D1%82

Тебе может это понравится...

Добавить комментарий