Skip to main content

how to store html form data in mysql database using hibernate | Java Servlet and hibernate Example

 

how to store html form data in mysql database using hibernate | Java Servlet and hibernate Example


For Explanation watch video:





Directory Structure




Pom.xml


<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>com.test</groupId>
<artifactId>Servlet-Hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Servlet-Hibernate Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>

</dependencies>
<build>
<finalName>Servlet-Hibernate</finalName>
</build>
</project>


form.html


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<style>
#div{
width:600px;
height:350px;
margin:auto;
margin-top:100px;
}
</style>
</head>
<body class="container-fluid">
<div class="card" id="div">
<h2 class="card-header text-center bg-danger text-light">Registration Form</h2>
<form action="register" method="post">
<table class="table table-hover table-striped">
<tr>
<td>Enter Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Enter Dob</td>
<td><input type="date" name="dob"></td>
</tr>
<tr>
<td>Enter Gender</td>
<td><input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female</td>
</tr>
<tr>
<td>Choose City</td>
<td><select name="city">
<option value="pune">Pune</option>
<option value="mumbai">Mumbai</option>
<option value="hyd">Hyd</option>
<option value="nagpur">Nagpur</option>
</select></td>
</tr>
<tr>
<td><input type="submit" value="register" class="btn btn-outline-success"></td>
<td><input type="reset" value="reset" class="btn btn-outline-danger"></td>
</tr>
</table>
</form>
</div>
</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>
  <welcome-file-list>
  <welcome-file>form.html</welcome-file>
  </welcome-file-list>
</web-app>


hibernate.cfg.xml



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

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/new</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hbm2ddl.auto">update</property>

<mapping class="com.entity.Employee" />
</session-factory>
</hibernate-configuration>



Utility.java


package com.utility;

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

public class Utiltity {
static SessionFactory factory = null;
static {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
factory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static Session getSession() {
Session ses = factory.openSession();
return ses;
}
}

Employee.java


package com.entity;

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

@Entity
@Table(name = "emptab")
public class Employee {
@Id
@GeneratedValue
private Integer eid;
@Column(name = "empname")
private String ename;
private String dob;
private String gender;
private String city;
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

SaveObject.java


package com.test;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.entity.Employee;
import com.utility.Utiltity;

public class SaveObject {
public static int save(Employee emp) {
//get the session Object
Session ses = Utiltity.getSession();
Transaction tx = null;
Integer count = 0;
try(ses){
//brgin the transaction
tx = ses.beginTransaction();
//save the object
count = (Integer) ses.save(emp);
//commit the trasaction
tx.commit();
}catch(HibernateException he) {
he.printStackTrace();
tx.rollback();
}catch(Exception e) {
e.printStackTrace();
tx.rollback();
}
return count;
}
}


RegisterServlet.java


package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.Employee;
import com.test.SaveObject;

@WebServlet("/register")
public class RegisterServlet extends  HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//get the printWriter
PrintWriter pw = res.getWriter();
//set Contenet Type
res.setContentType("text/html");
//read the form dat
String name = req.getParameter("name");
String dob = req.getParameter("dob");
String city = req.getParameter("city");
String gender = req.getParameter("gender");
Employee emp = new Employee();
emp.setCity(city);
emp.setDob(dob);
emp.setEname(name);
emp.setGender(gender);
int count = SaveObject.save(emp);
if(count==0) {
pw.println("<h2>Employee not registred</h2>");
pw.println("<a href='form.html'>Home</a>");
}else {
pw.println("<h2>Employee registred Successfully</h2>");
pw.println("<a href='form.html'>Home</a>");
}
//close the stream
pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}













Comments

Popular posts from this blog

Servlet Project Book Shop Application in eclipse

 Servlet Project Book Shop Application in eclipse  For explanation watch video::: Note :: In this Project you must configure web server (for example tomcat) with eclipse ide Download Bootstrap  from ::         https://getbootstrap.com/docs/4.3/getting-started/download/ Download mysql jar file from :: https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.22 adding MySQL Connector/J jar file in eclipse ide for jdbc video :: video link : https://youtu.be/4Fyd-k3eG_I Directory Structure:: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">   <welcome-file-list>     <welcome-file>home.html</welcome-file>   </welcome-file-list>   <display-...

JDBC basic example For Select Query

JDBC basic example For Select Query  For explanation watch video:  For Creating Table:: SQL> create table emp60(srno int,fname varchar2(10)); Table created. SQL> desc emp60;  Name                                      Null?    Type  ----------------------------------------- -------- ----------------------------  SRNO                                               NUMBER(38)  FNAME                                              VARCHAR2(10) SQL> insert into emp60 values(1,'allu'); 1 row created. SQL> insert into emp60 values(2,'vijay'); 1 row created. SQL> insert into emp60 values(3,'rajni'); 1 row created. SQL...

JDBC Program to access table data from mysql database

 import java.sql.*; class MysqlCon  { public static void main(String[] args)  { try{ Connection con = DriverManager.getConnection("jdbc:mysql:///new","root","root"); Statement st = con.createStatement(); String query = "select * from login"; ResultSet rs = st.executeQuery(query); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getString(2)); } con.close(); }catch(SQLException e){ System.out.println("Error"); }catch(Exception e){ } } }