Hibernate: aplicación web

Una aplicación web con hibernate es más fácil. Una página JSP es la mejor manera de obtener entradas de usuario. Esas entradas se pasan al servlet y, finalmente, se inserta en la base de datos mediante hibernate. Aquí la página JSP se usa para la lógica de presentación. La clase de servlet está destinada a la capa del controlador. La clase DAO está destinada a los códigos de acceso a la base de datos.

Herramientas y Tecnologías utilizadas en este proyecto:

  • JDK 1.6+ en adelante
  • Hibernate 3.6.3.Versiones finales o próximas
  • Eclipse
  • MySQL 5.5. o próximas versiones
  • Gato

Como Hibernate: la aplicación web se preparará, el proyecto se preparará como un proyecto web dinámico. Los siguientes frascos deben colocarse en la carpeta WEB-INF/lib

Página JSP de front-end que recibe información del usuario

registro.jsp

HTML

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration Form</title>
</head>
<style>
body {
    font-family: Verdana, Geneva, sans-serif;
    font-size: 14px;
    background: #006400;
}
.clearfix {
    &:after {
        content: "";
        display: block;
        clear: both;
        visibility: hidden;
        height: 0;
    }
}
.form_wrapper {
    background: #fff;
    width: 600px;
    max-width: 100%;
    box-sizing: border-box;
    padding: 25px;
    margin: 8% auto 0;
    position: relative;
    z-index: 1;
    border-top: 5px solid $yellow;
    -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    -webkit-transform-origin: 50% 0%;
    transform-origin: 50% 0%;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
    -webkit-transition: none;
    transition: none;
    -webkit-animation: expand 0.8s 0.6s ease-out forwards;
    animation: expand 0.8s 0.6s ease-out forwards;
    opacity: 0;
    h2 {
        font-size: 1.5em;
        line-height: 1.5em;
        margin: 0;
    }
    .title_container {
        text-align: center;
        padding-bottom: 15px;
    }
    h3 {
        font-size: 1.1em;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
    }
    label {
        font-size: 12px;
    }
    .row {
        margin: 10px -15px;
        >div {
            padding: 0 15px;
            box-sizing: border-box;
        }
    }
    .col_half {
        width: 50%;
        float: left;
    }
    .input_field {
        position: relative;
        margin-bottom: 20px;
        -webkit-animation: bounce 0.6s ease-out;
           animation: bounce 0.6s ease-out;
        >span {
            position: absolute;
            left: 0;
            top: 0;
            color: #333;
            height: 100%;
            border-right: 1px solid $grey;
            text-align: center;
            width: 30px;
            >i {
                padding-top: 10px;
            }
        }
    }
    .textarea_field {
        >span {
            >i {
                padding-top: 10px;
            }
        }
    }
    input {
    &[type="text"], &[type="email"], &[type="password"] {
      width: 100%;
      padding: 8px 10px 9px 35px;
      height: 35px;
      border: 1px solid $grey;
      box-sizing: border-box;
      outline: none;
      -webkit-transition: all 0.30s ease-in-out;
      -moz-transition: all 0.30s ease-in-out;
      -ms-transition: all 0.30s ease-in-out;
      transition: all 0.30s ease-in-out;
    }
    &[type="text"]:hover, &[type="email"]:hover, &[type="password"]:hover {
      background: #fafafa;
    }
    &[type="text"]:focus, &[type="email"]:focus, &[type="password"]:focus {
      -webkit-box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);
      -moz-box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);
      box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);
      border: 1px solid $yellow;
      background: #fafafa;
    }
    &[type="submit"] {
        background: $yellow;
        height: 35px;
        line-height: 35px;
        width: 100%;
        border: none;
        outline: none;
        cursor: pointer;
        color: #fff;
        font-size: 1.1em;
        margin-bottom: 10px;
        -webkit-transition: all 0.30s ease-in-out;
        -moz-transition: all 0.30s ease-in-out;
        -ms-transition: all 0.30s ease-in-out;
        transition: all 0.30s ease-in-out;
        &:hover {
            background: darken($yellow,7%);
        }
        &:focus {
            background: darken($yellow,7%);
        }
    }   
    &[type="checkbox"], &[type="radio"] {
      border: 0;
      clip: rect(0 0 0 0);
      height: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
    }
  }
}
.form_container {
    .row {
        .col_half.last {
            border-left: 1px solid $grey;
        }
    }
}
 
@-webkit-keyframes check {
  0% { height: 0; width: 0; }
  25% { height: 0; width: 7px; }
  50% { height: 20px; width: 7px; }
}
 
@keyframes check {
  0% { height: 0; width: 0; }
  25% { height: 0; width: 7px; }
  50% { height: 20px; width: 7px; }
}
 
@-webkit-keyframes expand {
    0% { -webkit-transform: scale3d(1,0,1); opacity:0; }
    25% { -webkit-transform: scale3d(1,1.2,1); }
    50% { -webkit-transform: scale3d(1,0.85,1); }
    75% { -webkit-transform: scale3d(1,1.05,1); }
    100% { -webkit-transform: scale3d(1,1,1);  opacity:1; }
}
 
@keyframes expand {
    0% { -webkit-transform: scale3d(1,0,1); transform: scale3d(1,0,1);  opacity:0; }
    25% { -webkit-transform: scale3d(1,1.2,1); transform: scale3d(1,1.2,1); }
    50% { -webkit-transform: scale3d(1,0.85,1); transform: scale3d(1,0.85,1); }
    75% { -webkit-transform: scale3d(1,1.05,1); transform: scale3d(1,1.05,1); }
    100% { -webkit-transform: scale3d(1,1,1); transform: scale3d(1,1,1);  opacity:1; }
}
 
 
@-webkit-keyframes bounce {
    0% { -webkit-transform: translate3d(0,-25px,0); opacity:0; }
    25% { -webkit-transform: translate3d(0,10px,0); }
    50% { -webkit-transform: translate3d(0,-6px,0); }
    75% { -webkit-transform: translate3d(0,2px,0); }
    100% { -webkit-transform: translate3d(0,0,0); opacity: 1; }
}
 
@keyframes bounce {
    0% { -webkit-transform: translate3d(0,-25px,0); transform: translate3d(0,-25px,0); opacity:0; }
    25% { -webkit-transform: translate3d(0,10px,0); transform: translate3d(0,10px,0); }
    50% { -webkit-transform: translate3d(0,-6px,0); transform: translate3d(0,-6px,0); }
    75% { -webkit-transform: translate3d(0,2px,0); transform: translate3d(0,2px,0); }
    100% { -webkit-transform: translate3d(0,0,0); transform: translate3d(0,0,0); opacity: 1; }
}
@media (max-width: 600px) {
    .form_wrapper {
        .col_half {
            width: 100%;
            float: none;
        }
    }
    .bottom_row {
        .col_half {
            width: 50%;
            float: left;
        }
    }
 
}
</style>
<body>
<div class="form_wrapper">
  <div class="form_container">
    <div class="title_container">
    <h1>GeekUser Registration Form</h1>
    <form action="register" method="post">
        <table cellpadding="3pt">
            <tr>
                <td>User Name :</td>
                <td><input type="text" name="userName" size="50" /></td>
            </tr>
            <tr>
                <td>Password :</td>
                <td><input type="password" name="password1" size="50" /></td>
            </tr>
 
            <tr>
                <td>Confirm Password :</td>
                <td><input type="password" name="password2" size="50" /></td>
            </tr>
            <tr>
                <td>email :</td>
                <td><input type="text" name="email" size="50" /></td>
            </tr>
            <tr>
                <td>Phone :</td>
                <td><input type="text" name="phone" size="50" /></td>
            </tr>
            <tr>
                <td>City :</td>
                <td><input type="text" name="city" size="50" /></td>
            </tr>
        </table>
        <p />
        <input type="submit" value="Register" />
    </form>
    </div>
    </div>
    </div>
</body>
</html>

Salida de esta página:

Output

Crear una clase Java, es decir, una clase POJO, una clase de controlador, una clase DAO

Clase de controlador > GeekUserControllerServlet.java

Java

import com.gfg.hibernate.dao.GeekUserDAO;
 
public class GeekUserControllerServlet extends HttpServlet {
     
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
        // From register.jsp, the controls
        // are passed to this controller servlet
        String userName = request.getParameter("userName");
        String password = request.getParameter("password1");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String city = request.getParameter("city");
        HttpSession session = request.getSession(true);
        try {
            GeekUserDAO userDAO = new GeekUserDAO();
            // Via DAO class addGeelUser method,
            // the data is inserted into the table
            userDAO.addGeekUser(userName, password, email, phone, city);
            // After that it is redirected to the success page
            response.sendRedirect("Success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Veamos la clase DAO> GeekUserDAO.java

Java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.gfg.hibernate.bean.GeekUser;
public class GeekUserDAO {   
    // Method to insert GeekUser in the database
    public Integer addGeekUser(String userName,
     String password,
     String email,
     String phone,
     String city) {
         SessionFactory sessionFactory;
            try {
                sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (Throwable ex) {
                System.err.println("Failed to create sessionFactory object." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            GeekUser geekUser = new GeekUser(userName, password, email,phone,city);
            employeeID = (Integer) session.save(geekUser);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employeeID;
    }
}

A través del método DAO, los detalles se insertan en la base de datos. Vemos que a través de la clase de bean GeekUser, se envían los datos. Veamos la clase POJO

Clase POJO > GeekUser.java

Java

public class GeekUser {
    // each and every attribute should have
    // the respective column in the database
    private int id;
    private String geekUserName;
    private String password;
    private String geekEmail;
    private String phone;
    private String city;   
    public GeekUser() {
         
    }
    // parameterized constructors are
    // necessary to carry the details
    public GeekUser(String userName,
     String password,
     String email,
     String phone,
     String city) {
        this.geekUserName = userName;
        this.password = password;
        this.geekEmail = email;
        this.phone = phone;
        this.city = city;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getGeekUserName() {
        return geekUserName;
    }
 
    public void setGeekUserName(String userName) {
        this.geekUserName = userName;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password1) {
        this.password = password1;
    }
 
    public String getGeekEmail() {
        return geekEmail;
    }
 
    public void setGeekEmail(String email) {
        this.geekEmail = email;
    }
 
    public String getPhone() {
        return phone;
    }
 
    public void setPhone(String phone) {
        this.phone = phone;
    }
 
    public String getCity() {
        return city;
    }
 
    public void setCity(String city) {
        this.city = city;
    }
 
}

Una vez que los detalles se agregan con éxito, se redirige a SuccessPage.java

Java

import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class SuccessPage extends HttpServlet {
 
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
 
        writer.println("<html>" + "<body bgcolor='#006400'>" + "<center><h3><font color='white'>"
                + "GeekUser details are added successfully via Hibernate. " + "</font></h3></center>" + "</body>"
                + "</html>");
    }
 
}

Veamos la salida del flujo:

Comprobemos los datos de la tabla también en paralelo.

Hibernate hace que el proceso sea mucho más fácil.

Se requiere una clase de bean (aquí es GeekUser.java). Todos y cada uno de los atributos de una clase de bean deben mapearse en un archivo hbm (archivo de mapeo de hibernación). Es un archivo XML donde todos y cada uno de los atributos se asignan perfectamente a la tabla en la base de datos.

geekuser.hbm.xml (archivo de asignación que asigna atributos de clase de bean (POJO) a la tabla correspondiente)

XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- GeekUser bean class is mapped to GEEKUSER table -->
    <class name="com.gfg.hibernate.bean.GeekUser" table="GEEKUSER">
        <!-- This makes id attribute to be of int datatype and Primary Key -->
        <id column="id" name="id" type="int">
            <generator class="native"/>
           </id>
        <!-- geekUserName,password,geekEmail,phone and city
             are the other attributes that need to be mapped -->
        <property column="geekUserName" name="geekUserName" type="java.lang.String" />
        <property column="password" name="password" type="string" />
        <property column="geekEmail" name="geekEmail" type="java.lang.String" />
        <property column="phone" name="phone" type="java.lang.String" />
        <property column="city" name="city" type="java.lang.String" />
    </class>
</hibernate-mapping>

Archivo de configuración principal de hibernación > hibernate.cfg.xml

XML

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- As we are going to connect with mysql, this is required -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/geeksforgeeks</property>
        <property name="hibernate.connection.username">root</property>
        <!-- Provide your correct password here -->
        <property name="hibernate.connection.password">XXXX</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
          <!-- In order to show the SQL query in console, this is required -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">create </property>
        <!-- Specification of exact hibernate mapping file need to be specified -->
        <mapping resource="com/gfg/hibernate/bean/geekuser.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Como esta es la aplicación web, veamos también web.xml, que ayudará al flujo de datos de jsp a servlet.

XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>HibernateWebApp</display-name>
    <servlet>
        <display-name>User</display-name>
        <servlet-name>User</servlet-name>
        <servlet-class>com.gfg.hibernate.controller.GeekUserControllerServlet</servlet-class>
    </servlet>
    <servlet>
        <display-name>Success</display-name>
        <servlet-name>Success</servlet-name>
        <servlet-class>com.gfg.hibernate.controller.SuccessPage</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>User</servlet-name>
        <url-pattern>/register</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Success</servlet-name>
        <url-pattern>/Success</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>register.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Archivo de video del proyecto:

Conclusión

En este tutorial, hemos visto que mediante el uso de la función muy agradable de hibernación, los datos se insertan en la tabla de la base de datos de una manera más fácil. Una cosa más importante es que para cualquier tipo de base de datos, esto funciona. Si estamos cambiando una base de datos diferente, necesitamos cambiar hibernate.cfg.xml para admitirlo

XML

<!-- for sql server -->
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.connection.driver_class">com.microsoft.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc.Microsoft://localhost/<dbname></property>
        <property name="hibernate.connection.username">root</property>
          <!-- Need to change proper password -->
        <property name="hibernate.connection.password">****</property>
    </session-factory>
</hibernate-configuration>
  <!-- for oracle -->
  <session-factory>
    <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:dbname</property>
    <property name="connection.username">user</property>
    <property name="connection.password">***</property>
    <property name="dialect">org.hibernate.dialect.Oracle8iDialect</property>    
    <property name="show_sql">true</property>     
  </session-factory>
  <!-- Similarly for other database, it has to be specified

Publicación traducida automáticamente

Artículo escrito por priyarajtt y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *