Spring MVC Hibernate CRUD Example With Maven - onlyxcodes

Wednesday 17 August 2022

Spring MVC Hibernate CRUD Example With Maven

I'll describe how to create a straightforward CRUD application with Spring MVC and Hibernate in this post. For the project, I utilized Maven as a build tool and MySQL as the database.


A Web MVC framework called Spring MVC is used to create web apps. The same as spring boot, spring-security, etc., it is a spring module. Model-View-Controller architecture is known as MVC.


In this example, we'll create a straightforward CRUD application for corporate information that will concentrate on the Spring MVC module.


spring mvc hibernate crud example with maven

Table Content

1. Create Maven Web Project Using Eclipse IDE

2. Project Directory Structure

3. Create A Database

4. Add Dependencies

5. Spring WebMVC Configuration

6. Spring Bean Configuration

7. Create Model or Entity Class

8. Create Dao Class

9. Create Controller Class

10. View Pages


1. Create Maven Web Project Using Eclipse IDE

In your Eclipse IDE, select File->New->Maven Project to start a new Maven project.


in your eclipse ide, select file->new->maven project to start a new maven project.

The opening of a new wizard. Keep the default setting for the workspace location, or you can provide a new workspace if you'd prefer to put the project there.


select project location where you want to store this example

You will be required to select the archetype from the list in the following stage.


We are given a variety of archetypes to pick from for various projects. We'll use maven-archetype-webapp for our project because we're going to implement a web project, as you can see below:


select maven-archetype-webapp

The project group ID and Artifact ID must be entered in the upcoming wizard step, and the project package name will be pre-populated as necessary.


Please enter the project name as the Artifact id. As you can see in the screenshot below, I'm supplying the name "mvcapp" for this tutorial.


Simply click the Finish button to finish the initial Maven project creation.


enter the project name as the artifact id

2. Project Directory Structure

The full directory structure, including the classes and packages we'll be creating for this example, is shown below.


project directory structure

3. Create A Database

Create the "spring_mvc_crud_db" database in PhpMyAdmin first.


Once this application has been finished, if you start it, Hibernate will automatically populate the Company name table.


CREATE DATABASE spring_mvc_crud_db

4. Add Dependencies

For our project, we now need to add dependencies. With Maven, you have the highly practical option of having all necessary dependencies downloaded from the Maven repository automatically.


The maven project has an XML file (pom.xml) where we need to put our dependencies list. Maven will then download and make available all necessary jar files for us.


The following dependencies are required for our Spring MVC project.


You may always look for a dependency on the maven repositories website, copy the dependency XML tag for the version you want from there, and then paste it into your pom.xml file.


Spring MVC Dependency :


We use the dependency listed below when using Spring MVC for web development.


The MVC functionality for Servlet environments is enabled by spring-webmvc.


Since spring-webmvc depends on spring-web, utilizing spring-webmvc does not necessitate explicitly specifying spring-web.


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.22</version>
</dependency>

Spring ORM Dependency:


We need to mention the following dependency if we use Spring Data JPA.


Support for Hibernate and JPA, including HibernateTemplate and JpaTemplate, is included with this dependency.


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.3.18</version>
</dependency>

MySQL Dependency:


Because we use the MySQL database in this application, we need to be dependent on the MySQL JDBC driver:


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

Hibernate Core Dependency:


Since Hibernate is one of the JPA providers we'll be using, we add the following dependency.


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

JSTL Dependency:


We add the dependency for the JavaServer Pages Tag Library. We will build standard operations like looping and others using this dependency.


<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

JSP and Servlet Dependency:


In our project, we additionally employ Servlet and JSP Dependency to prevent more issues.

<dependency>
	<groupId>org.apache.tomcat</groupId>
	<artifactId>jsp-api</artifactId>
	<version>6.0.32</version>
	<scope>provided</scope>
</dependency>

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>servlet-api</artifactId>
	<version>2.5</version>
	<scope>provided</scope>
</dependency>

The pom.xml file for our Spring MVC example can be seen below. It contains a list of all the dependencies I required, along with their versions.


Note:- Please be aware that we may have updated versions of these dependencies by the time you read this article, and it is always advised to use the most recent stable version.


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.onlyxcodes</groupId>
  <artifactId>mvcapp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>mvcapp 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>javax.servlet</groupId>
	    <artifactId>servlet-api</artifactId>
	    <version>2.5</version>
	    <scope>provided</scope>
	</dependency>
	
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>5.3.22</version>
	</dependency>
	
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-orm</artifactId>
	    <version>5.3.18</version>
	</dependency>
	
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>8.0.30</version>
	</dependency>
	
	<dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-core</artifactId>
	    <version>5.6.9.Final</version>
	</dependency>
	
	<dependency>
	    <groupId>jstl</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	
	<dependency>
		<groupId>org.apache.tomcat</groupId>
		<artifactId>jsp-api</artifactId>
		<version>6.0.32</version>
		<scope>provided</scope>
	</dependency>
	
  </dependencies>
  
  <build>
    <finalName>mvcapp</finalName>
  </build>
</project>

5. Spring WebMVC Configuration

The web.xml file is created and placed in the WEB-INF/src/main/webapp folder.


We must use the web.xml file and define our dispatcher servlet inside of it in a conventional XML configurations-based Spring MVC application. We must then build another XML file specifically for our dispatcher servlet.


In the web.xml file, DispatcherServlet is defined here. In Spring web applications, the front controller is the DispatcherServlet.


All client requests are accepted by the DispatcherServlet, which forwards them to the appropriate controller. A controller responds to clients after its task is complete.


The web container will look for the web.xml and will scan the entire file when we execute the application because web.xml is a deployment descriptor and serves as the access point.


<!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>spring</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>spring</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

6. Spring Bean Configuration

The spring-servlet.xml file is created in the WEB-INF/src/main/webapp folder.


The main portion, where some XML setup connects Spring and Hibernate, is now at hand. Open the spring-servlet.xml file located in the WEB-INF/spring-servlet.xml directory and make the following changes to it.


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans.xsd
	   http://www.springframework.org/schema/context
	   http://www.springframework.org/schema/context/spring-context.xsd
	   http://www.springframework.org/schema/tx
	   http://www.springframework.org/schema/tx/spring-tx.xsd
    ">
    
    <context:component-scan base-package="mvcapp"></context:component-scan>
    
    <bean
     	class="org.springframework.web.servlet.view.InternalResourceViewResolver"
     	name="viewResolver">

        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp"></property>
        
    </bean>
    
    <!-- data source bean -->

    <bean
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        name="ds">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"  value="jdbc:mysql://localhost:3306/spring_mvc_crud_db" />
        <property name="username" value="root" />
        <property name="password" value="" />

    </bean>
    

    <!-- LocalSessionFactoryBean -->
    
    <bean
         class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
         name="factory">

        <!-- data source -->
        <property name="dataSource" ref="ds"></property>

        <!-- hibernate properties -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <!-- annotated classes -->
        <property name="annotatedClasses">
            <list>
                <value>mvcapp.model.Company</value>
            </list>
        </property>

    </bean>
    
    
    <bean class="org.springframework.orm.hibernate5.HibernateTemplate"
          name="hibernateTemplate">
        <property name="sessionFactory" ref="factory"></property>

    </bean>
    
    <tx:annotation-driven/>
        
    <bean
         class="org.springframework.orm.hibernate5.HibernateTransactionManager"
         name="transactionManager">
        <property name="sessionFactory" ref="factory"></property>
    </bean>
    
   
</beans>    

Explanation:


Configure Base Package Scan:


The auto scanning function in Spring is enabled by the "context:component" option.


The basic package tells Spring where to look for your components; whenever it locates a bean, it registers it in the Spring container.


In essence, <context:component-scan> finds the annotations by scanning the packages. To put it another way, it instructs Spring to scan which packages for the annotated beans or components.


The following are some of the ones that <context:component-scan> can identify: @Component, @Repository, @Service, @Controller, @RestController, and @Configuration.


If you wish to use a different package for spring to search for a controller, please modify <context:component-scan base-package= "">.


I used the name "mvcapp." because the "mvcapp" package comes before my other sub-packages.


<context:component-scan base-package="mvcapp"></context:component-scan>

Configure Spring MVC View Resolvers :


The declaration for a common view resolver is shown below, which transforms logical view names into real JSP pages.


<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    name="viewResolver">

    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp"></property>
        
</bean>

Before configuring the DataSource, SessionFactory, and HibernateTemplate beans, please review the diagram below to understand how their class objects interact.


hibernate template

Configure DataSource Bean:


We are supplying all the data from the MySQL database in this bean.


The database's URL, username, and password should be modified to reflect your environment's values.


Injection of the data source (ds) into the LocalSessionFactoryBean is described below.


<!-- data source bean -->

<bean
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    name="ds">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url"  value="jdbc:mysql://localhost:3306/spring_mvc_crud_db" />
    <property name="username" value="root" />
    <property name="password" value="" />
</bean>

Configure SessionFactory Bean:


Below, we configure the LocalSessionFactoryBean.


Through a LocalSessionFactoryBean, which is a FactoryBean that builds a Hibernate's SessionFactory, Spring offers support for the Hibernate SessionFactory.


A DataSource bean that has already been declared is necessary for LocalSessionFactoryBean.


Look at how the LocalSessionFactoryBean class object uses the data source (ds) object.


Additionally, the LocalSessionFactoryBean class object includes annotatedClasses and hibernateProperties.


Many Hibernate services, such as automatic table generation using hbm2ddl.auto, are enabled.


Recognize the mvcapp.model.


Company:- Our model class, The Company, is stored in the mvcapp.model package.


The HibernateTemplate class uses the LocalSessionFactoryBean class.


<!-- LocalSessionFactoryBean -->
    
<bean
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
    name="factory">

    <!-- data source -->
    <property name="dataSource" ref="ds"></property>

    <!-- hibernate properties -->
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>

    <!-- annotated classes -->
    <property name="annotatedClasses">
        <list>
            <value>mvcapp.model.Company</value>
        </list>
    </property>

</bean>

Configure HibernateTemplate Bean:


The hibernate5.org.springframework.orm. A helper class called HibernateTemplate offers many ways to query or get data from the database.


We will use this HibernateTemplate class object in the Dao class to carry out CRUD operations on the database.


<bean class="org.springframework.orm.hibernate5.HibernateTemplate"
    name="hibernateTemplate">
    <property name="sessionFactory" ref="factory"></property>

</bean>

A transactionManager bean must be constructed to handle annotation-based transaction setup; <tx:annotation-driven />uses this bean to manage transactions.


For the SessionFactory's automatic transaction support, make the following declaration:


<tx:annotation-driven/>
        
<bean
    class="org.springframework.orm.hibernate5.HibernateTransactionManager"
    name="transactionManager">
    <property name="sessionFactory" ref="factory"></property>
</bean>

7. Create Model or Entity Class

We develop a @Entity-annotated class in the model package.


The company classifies this entity.


Java will serve as a mapping to the "company" database table. Additionally, this entity class will be used as a reference by the hibernate ORM for database operations at the DAO layer.


The @Entity annotation identifies the entity class as such, and it is a POJO with variables, associated getters, and setters.


We don't need to use the @Table annotation because the table name and class name in this case are the same.


The field id has the annotations @Id and @GeneratedValue to show that it is the primary key and that its value is created automatically.


Our entity class corresponds to the MySQL database's company table. Due to their similar names, the fields "name" and "headquarter" are not tagged with the @Column annotation.


Company.java


package mvcapp.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Company {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;
	private String headquarter;
	
	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 String getHeadquarter() {
		return headquarter;
	}
	public void setHeadquarter(String headquarter) {
		this.headquarter = headquarter;
	}
	public Company() {
		super();
	}
	public Company(int id, String name, String headquarter) {
		super();
		this.id = id;
		this.name = name;
		this.headquarter = headquarter;
	}
	@Override
	public String toString() {
		return "Company [id=" + id + ", name=" + name + ", headquarter=" + headquarter + "]";
	}
	
}

8. Create Dao Class

We develop the CompnayDao DAO class. The DAO class is responsible for carrying out all CRUD operations on the database directly.


This class is identified as a bean by the annotation @Component.


Here, the HibernateTemplate class object is injected. The methods in this class make it easier to do insert, update, and delete operations.


void saveOrUpdate(company): If an ID is detected, the record is updated; otherwise, it is saved.


List loadAll(Company.class): retrieves all of the model class (Company) property's records.


load(Company.class, cid):  based on the supplied id, returns the model object.


void delete(company): removes the specified model object based on its id.


get(Company.class, cid): based on the supplied id, returns the model object.


@Transactional annotation is present in the class. This annotation will cause Spring to insert transaction support code into any methods that it finds.


CompanyDao.java


package mvcapp.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;

import mvcapp.model.Company;

@Component
public class CompanyDao {
	
	@Autowired
	private HibernateTemplate hibernateTemplate;
	
	//create a new company
	@Transactional
	public void createCompany(Company company)
	{
		this.hibernateTemplate.saveOrUpdate(company);
	}
	
	//get all company
	public List<Company> getAllCompany()
	{
		List<Company> company = this.hibernateTemplate.loadAll(Company.class);
		return company;
	}
	
	//delete a single company
	@Transactional 
	public void deleteCompany(int cid)
	{
		Company company = this.hibernateTemplate.load(Company.class, cid);
		this.hibernateTemplate.delete(company);
	}
	
	//get a single company
	public Company getSingleCompany(int cid)
	{
		return this.hibernateTemplate.get(Company.class, cid);
	}

}

9. Create Controller Class

Make a CompanyController.java controller class for the Spring MVC framework. This controller class's @Controller annotation identifies it as a controller class.


The controller class responds to each user request that the dispatcher servlet sends to it.


We are implementing methods for various client request types in this controller class.


A technique for controlling navigation is also requested, allowing users to go back to the main page from any other page. 


The requests are to get all companies, add a new company, modify an existing company, delete a company, and get all companies.


Here, the CompnayDao class object was injected using the @Autowired annotation.


As we layer our logic in Controller, we are calling methods from the CompanyDao class in this class.


CompanyController.java


package mvcapp.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.RedirectView;

import mvcapp.dao.CompanyDao;
import mvcapp.model.Company;

@Controller
public class CompanyController {
	
	@Autowired
	private CompanyDao companyDao;
	
	@RequestMapping("/")
	public String home(Model model)
	{
		List<Company> company= companyDao.getAllCompany();
		model.addAttribute("companies", company);
		return "index";
	}
	
	//shows add company form 
	@RequestMapping("/add-company")
	public String addCompany(Model model)
	{
		model.addAttribute("title", "Add Company");
		return "add_company";
	}
	
	//handle add company form request
	@RequestMapping(value="/submit-company",  method=RequestMethod.POST)
	public RedirectView handleCompany(@ModelAttribute Company company, HttpServletRequest request)
	{
		companyDao.createCompany(company);
		RedirectView redirectView = new RedirectView();
		redirectView.setUrl(request.getContextPath()+ "/");
		return redirectView;
	}
	
	//delete handle request
	@RequestMapping("/delete/{companyId}")
	public RedirectView deleteCompany(@PathVariable("companyId") int id, HttpServletRequest request)
	{
		companyDao.deleteCompany(id);
		RedirectView redirectView = new RedirectView();
		redirectView.setUrl(request.getContextPath()+ "/");
		return redirectView;
	}
	
	//show update company form
	@RequestMapping("/update/{companyId}")
	public String updateCompanyForm(@PathVariable("companyId") int id, Model model)
	{
		Company company = this.companyDao.getSingleCompany(id);
		model.addAttribute("company", company);
		return "update_company";
	}

}

Explanation:


Retrieve All Records


The index.jsp page is returned by the home() method.


To retrieve all records, we call the getAllCompany() method of the Company Dao class using a CompanyDao object.


An interface in Spring called the Spring Model is used to add attributes to the model. Data from the controller is mostly rendered using it on the view page.


We added the "companies" attribute and a company class object to the addAttribute() method.


@RequestMapping("/")
public String home(Model model)
{
	List<Company> company= companyDao.getAllCompany();
	model.addAttribute("companies", company);
	return "index";
}

Show Form to Add New Company Record


The add_company.jsp page is returned by the addCompany() method.


The add-company URL is associated with this controller action via the @RequestMapping annotation. The file add_company.jsp page is displayed when the hyperlink for Add New is clicked.


We just send "title" and the title value to the addAttribute() method using the model object.


//shows add company form 
@RequestMapping("/add-company")
public String addCompany(Model model)
{
	model.addAttribute("title", "Add Company");
	return "add_company";
}

Add New Company Record


The handleCompany() method is developed with the RedirectView return type.


In this controller method, we interact with the Add New Company Form Post. The @RequestMapping annotation indicates that this controller method will be mapped to the POST's /submit-company URL and HTTP request method.


As you can see, we annotated using @ModelAttribute. This annotation retrieves the fields from the insert form and binds them to the Company model class object.


To add a new record to the database, we call the createCompany() method using the CompanyDao object and paste the company object in this method.


We use the HttpServletRequest object to obtain the contextPath within the setUrl() method. The request in this example is the HttpServletRequest object.


The name of our application ContextPath appears in the URI immediately behind the port number, followed by a "/" (black slash).


The home page, "/," is then returned by returning the redirect view object.


//handle add and update company form request
@RequestMapping(value="/submit-company",  method=RequestMethod.POST)
public RedirectView handleCompany(@ModelAttribute Company company, HttpServletRequest request)
{
	companyDao.createCompany(company);
	RedirectView redirectView = new RedirectView();
	redirectView.setUrl(request.getContextPath()+ "/");
	return redirectView;
}

Delete Company Record


The deleteCompany() method is developed with the RedirectView return type.


The @PathVariable annotation in spring binds URI template variables to handler method arguments for a controller. The following variables of one or more paths are contained within braces ({ }) in a URI template.


http:/localhost:8080/delete/id


example


http:/localhost:8080/delete/5


The @PathVariable annotation in this case links the id variable to the URI variable companyId.


To remove the URI id value record from the database, we use the deleteCompany() method using the CompanyDao object and paste the id variable in this method.


We use the HttpServletRequest object to obtain the contextPath within the setUrl() method. The request in this example is the HttpServletRequest object.


The "/" or index page is then returned after we have returned the redirect view object.


//delete handle request
@RequestMapping("/delete/{companyId}")
public RedirectView deleteCompany(@PathVariable("companyId") int id, HttpServletRequest request)
{
	companyDao.deleteCompany(id);
	RedirectView redirectView = new RedirectView();
	redirectView.setUrl(request.getContextPath()+ "/");
	return redirectView;
}

Update Existing Company Record


The updateCompanyForm() method is created, and it returns the update_company.jsp page.


The @PathVariable annotation in this case links the id variable to the URI variable companyId.


To retrieve the URI id value record from the database, we use the getSingleCompany() method using the CompanyDao object and paste the id variable in this method.


The "company" attribute and company object were supplied using the model object in the addAttribute() method.


In the update_company.jsp page, we will render the "company" attribute.


//show update company form
@RequestMapping("/update/{companyId}")
public String updateCompanyForm(@PathVariable("companyId") int id, Model model)
{
	Company company = this.companyDao.getSingleCompany(id);
	model.addAttribute("company", company);
	return "update_company";
}

10. View Pages


common.jsp

The standard JSP file is this one. Bootstrap CSS and JS tags can be found in this file.


I set the JSTL (JavaServer Pages Standard Tag Library) tag in this file.


We will incorporate this file into our other JSP pages.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<meta name="viewport" content="width=device-width, initial-scale=1">

<%@page isELIgnored="false" %>    
 
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />  

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />  
    
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>


<title><c:out value="${title}">Spring MVC Hibernate CRUD Example With Maven</c:out></title>

index.jsp

This is our index page, and the tabular formatted database records are shown here.


See the code on line 6 of the common.jsp file that was included.


The "items" attribute of the <c:forEach> tag iterates the collection of "companies" entries.


Here, the attribute "companies" is derived from the home() method that we previously covered in the controller codes.


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <%@include file="./common.jsp"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg bg-light">
	  <div class="container-fluid">
	    <a class="navbar-brand" href="https://www.onlyxcodes.com/">Onlyxcodes</a>
	    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
	      <span class="navbar-toggler-icon"></span>
	    </button>
	    <div class="collapse navbar-collapse" id="navbarScroll">
	      <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
	        <li class="nav-item">
	          <a class="nav-link active" aria-current="page" href="https://www.onlyxcodes.com/2022/08/spring-mvc-hibernate-crud-example-with-maven.html">Back to Tutorial</a>
	        </li>
	      </ul>
	    </div>
	  </div>
	</nav>
	
	<div class="container mt-3">
	
		<div class="row">
		
			<h3 class="text-center mb-3" style="color:red;">Spring MVC CRUD With MySQL & Hibernate</h3>
			
			<table class="table mt-4">
			  <thead class="table-light">
			    <tr>
			      <th scope="col">Id</th>
			      <th scope="col">Company Name</th>
			      <th scope="col">Headquarter</th>
			      <th scope="col">Edit</th>
			      <th scope="col">Delete</th>
			    </tr>
			  </thead>
			  <tbody class="table-group-divider">
			  
			  	<c:forEach items="${companies}" var="str">
				    <tr>
				      <th scope="row">${str.id}</th>
				      <td>${str.name}</td>
				      <td>${str.headquarter}</td>
				      <td><a href="update/${str.id}"><i class="fas fa-edit"></i></a></td>
				      <td><a href="delete/${str.id}"><i class="fas fa-trash-alt text-danger"></i></a></td>
				    </tr>
			    </c:forEach>
			    
			  </tbody>
			</table>
			
			<div class="container text-center">
				<a href="add-company" class="btn btn-success">Add Company</a>
			</div>
			
		</div>
	</div>
	
  </body>
</html>

Two hyperlinks that enable you to edit and delete particular company records are visible on this page.


<td><a href="update/${str.id}"><i class="fas fa-edit"></i></a></td>
<td><a href="delete/${str.id}"><i class="fas fa-trash-alt text-danger"></i></a></td>

The last element is a link. The end URL for this hyperlink is "add-company."


The controller method to display the add_company.jsp file is indicated by the "add-company" URL.


The form to add new company entries is located in the add_company.jsp file.


<a href="add-company" class="btn btn-success">Add Company</a>

index page - spring with hibernate crud example using annotations - how to fetch data from database in spring mvc

add_company.jsp

The form for adding new company records is in the file.


<form action="submit-company" method="post">

Look at this form tag's value for the action attribute, submit-company.


When this form is submitted, the handleCompany() method in the controller code will be used to reach the controller class via the URL /submit-company.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<%@include file="./common.jsp"%>
</head>
<body>
	<nav class="navbar navbar-expand-lg bg-light">
		<div class="container-fluid">
		  <a class="navbar-brand" href="https://www.onlyxcodes.com/">Onlyxcodes</a>
		  <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
		    <span class="navbar-toggler-icon"></span>
		  </button>
		  <div class="collapse navbar-collapse" id="navbarScroll">
		    <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
		      <li class="nav-item">
		        <a class="nav-link active" aria-current="page" href="https://www.onlyxcodes.com/2022/08/spring-mvc-hibernate-crud-example-with-maven.html">Back to Tutorial</a>
		      </li>
		    </ul>
		  </div>
		 </div>
	 </nav>
	<div class="container mt-3">
		<div class="row">
			<div class="col-md-6 offset-md-3">
				<h1 class="text-center mb-3">Enter Company Detail</h1>
				<form action="submit-company" method="post">
					  <div class="mb-3">
					    <label class="form-label">Company Name</label>
					    <input type="text" name="name" class="form-control" placeholder="type company name">
					  </div>
					  <div class="mb-3">
					    <label class="form-label">Headquarter</label>
					    <input type="text" name="headquarter" class="form-control" placeholder="type headquater or location">
					  </div>
					  <div class="container text-center">
						  <button type="submit" class="btn btn-primary">Create</button>
						  <a href="${pageContext.request.contextPath}/" class="btn btn-outline-danger">Back</a>
					  </div>
				</form>
			</div>	
		</div>
	</div>
</body>
</html>

the form for adding new company records is in the file - spring boot

update_company.jsp

An updated form can be found in this file.


This file displays a company's current record.


We can notice a hyperlink in the index file that enables editing of particular company data.


<a href="update/${str.id}"><i class="fas fa-edit"></i></a>

The updateCompanyForm() method of the controller displays the update form along with the previously edited record.


We retrieve the "company" attribute from the updateCompanyForm() method, which we previously mentioned in the controller codes, in this file.


We display existing ID entries that users click through the edit hyperlink using the "company" attribute.


The form for updating new company records is in the file.


Look at this form tag's value for the action attribute, submit-company.


<form action="${pageContext.request.contextPath}/submit-company" method="post">

After the revised form has been submitted, the handleCompany() methods of the controller class are once more accessed via the URL /submit-company.


Before closing the </form> element, check for a hidden input type tag. The value of the editing id tag is used to update records that have already been created.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<%@include file="./common.jsp"%>
</head>
<body>
	<nav class="navbar navbar-expand-lg bg-light">
	  <div class="container-fluid">
	    <a class="navbar-brand" href="https://www.onlyxcodes.com/">Onlyxcodes</a>
	    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
	      <span class="navbar-toggler-icon"></span>
	    </button>
	    <div class="collapse navbar-collapse" id="navbarScroll">
	      <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
	        <li class="nav-item">
	          <a class="nav-link active" aria-current="page" href="https://www.onlyxcodes.com/2022/08/spring-mvc-hibernate-crud-example-with-maven.html">Back to Tutorial</a>
	        </li>
	      </ul>
	    </div>
	   </div>
	 </nav>
	<div class="container mt-3">
		<div class="row">
			<div class="col-md-6 offset-md-3">
				<h1 class="text-center mb-3">Update Company Detail</h1>
				<form action="${pageContext.request.contextPath}/submit-company" method="post">
					  <div class="mb-3">
					    <label class="form-label">Company Name</label>
					    <input type="text" name="name" class="form-control" value="${company.name}">
					  </div>
					  <div class="mb-3">
					    <label class="form-label">Headquarter</label>
					    <input type="text" name="headquarter" class="form-control" value="${company.headquarter}">
					  </div>
					  <div class="container text-center">
						  <button type="submit" class="btn btn-warning">Update</button>
						  <a href="${pageContext.request.contextPath}/" class="btn btn-outline-danger">Back</a>
					  </div>
					  <input type="hidden" name="id" value="${company.id}">
				</form>
			</div>	
		</div>
	</div>
</body>
</html>

updated form - java based configuration

No comments:

Post a Comment

Post Bottom Ad