Spring boot AngularJS示例

时间:2020-02-23 14:35:46  来源:igfitidea点击:

在本教程中,我们将看到如何创建Spring Boot AngularJS示例。

我们将使用Spring Boot 1.5.3发布版本,它配有Hibernate 5.

我们将创建一个Spring Boot AngularJS应用程序,它将具有AngularJS作为用户界面。

它将提供用户界面,我们可以从中添加,更新或者删除客户数据库。
我们将使用控制器,服务和DAO类来实现这些功能。
我们将使用SessionFactory类Hibernate连接到MySQL数据库。

用于创建以下项目的工具:

  • Spring boot 1.5.3.Release.
  • Spring4.3.8.Release.
  • Tomcat Embed 8.
  • Maven 3.
  • Java 8.
  • Eclipse
  • Hibernate 5.3.5.
  • mysql 5.7.18

第1步:使用名为"springboottangularjsexample"的Eclipse中的Maven创建动态Web项目。

第2步:更改"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>org.igi.theitroad</groupId>
	<artifactId>SpringBootHibernateExample</artifactId>
 
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootHibernateExample Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.3.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- JSTL for JSP -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
 
		<!-- For JSP compilation -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.threeten/threetenbp -->
		<dependency>
			<groupId>org.threeten</groupId>
			<artifactId>threetenbp</artifactId>
			<version>0.7.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringBootHibernateExample</finalName>
	</build>
</project>

Spring-Boot-Starter-Parent为我们提供任何Spring项目所需的所有Maven默认值。
由于我们正在开发Web应用程序,我们还需要添加Spring-Boot-Starter-Web依赖项,并且我们还需要包含Pring-Boot-Starter-Data-JPA以将此应用程序运行Hibernate。

我们还需要将MySQL-Connector-Java放入MySQL JDBC驱动程序。
如果我们使用的是任何其他数据库,则需要使用不同的数据库连接器。
让我们首先进行Hibernate配置。

Hibernate配置

第3步:在Package .org.igi.theitroad中创建名为"hibernateConfiguration.java"的文件

package org.igi.theitroad;	
import java.util.Properties;
 
import javax.sql.DataSource;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {
	@Value("${db.driver}")
	private String DRIVER;
 
	@Value("${db.password}")
	private String PASSWORD;
 
	@Value("${db.url}")
	private String URL;
 
	@Value("${db.username}")
	private String USERNAME;
 
	@Value("${hibernate.dialect}")
	private String DIALECT;
 
	@Value("${hibernate.show_sql}")
	private String SHOW_SQL;
 
	@Value("${hibernate.hbm2ddl.auto}")
	private String HBM2DDL_AUTO;
 
	@Value("${entitymanager.packagesToScan}")
	private String PACKAGES_TO_SCAN;
 
	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(DRIVER);
		dataSource.setUrl(URL);
		dataSource.setUsername(USERNAME);
		dataSource.setPassword(PASSWORD);
		return dataSource;
	}
 
	@Bean
	public LocalSessionFactoryBean sessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
		Properties hibernateProperties = new Properties();
		hibernateProperties.put("hibernate.dialect", DIALECT);
		hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
		hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
		sessionFactory.setHibernateProperties(hibernateProperties);
 
		return sessionFactory;
	}
 
	@Bean
	public HibernateTransactionManager transactionManager() {
		HibernateTransactionManager transactionManager = new HibernateTransactionManager();
		transactionManager.setSessionFactory(sessionFactory().getObject());
		return transactionManager;
	}	
}

上面的类是用@configuration和@bean注释注释。
这些注释用于在Spring 中定义 Bean。

@Configuration类似于<bean>标记在Spring XML配置中,@Bean类似于<bean>标记。

@Value注释用于从属性文件注入变量。
在这种情况下,它将从Application.properties中读取,我们将在下一步中创建。

第4步:在包/src/main /资源中创建名为"application.properties"的文件

logging.level=DEBUG
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/CustomerData
db.username: root
db.password: admin
 
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: org
 
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

模型类

第5步:在Package .org.igi.theitroad.model中创建名为"customer.java"的文件

package org.igi.theitroad.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;
 
/*
 * This is our model class and it corresponds to Customer table in database
 */
@Entity
@Table(name="CUSTOMER")
public class Customer{
 
	@Id
	@Column(name="id")
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	int id;
 
	@Column(name="customerName")
	String customerName; 
 
	@Column(name="email")
	String email;
 
	public Customer() {
		super();
	}
	public Customer(String customerName,String email) {
		super();
		this.customerName=customerName;
		this.email=email;
	}
	public String getCustomerName() {
		return customerName;
	}
	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
}

@entity用于制作持久的POJO类。

对于此Java类,我们将在数据库中具有相应的表。
@column用于将注释属性映射到表中的相应列。

创建客户表:

使用以下DDL在数据库中创建客户表。

CREATE TABLE CUSTOMER (
id int(11) NOT NULL AUTO_INCREMENT,
customerName varchar(255) DEFAULT NULL,
email varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
)

控制器类

第6步:在包中创建一个名为"customercontroller.java"的文件.igi.theitroad.Controller

package org.igi.theitroad.controller;
 
import java.util.List;
 
import org.igi.theitroad.model.Customer;
import org.igi.theitroad.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class CustomerController {
 
	@Autowired
	CustomerService customerService;
 
	@RequestMapping(value = "/getAllCustomers", method = RequestMethod.GET, headers = "Accept=application/json")
	public List<Customer> getAllCustomers(Model model) {
 
		List<Customer> listOfCustomers = customerService.getAllCustomers();
		model.addAttribute("customer", new Customer());
		model.addAttribute("listOfCustomers", listOfCustomers);
		return listOfCustomers;
	}
 
	@RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json")
	public String goToHomePage() {
		return "redirect:/getAllCustomers";
	}
 
	@RequestMapping(value = "/getCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
	public void getCustomerById(@PathVariable int id) {
		customerService.getCustomer(id);
	}
 
	@RequestMapping(value = "/addCustomer", method = RequestMethod.POST, headers = "Accept=application/json")
	public Customer addCustomer(@RequestBody Customer customer) {
		return customerService.addCustomer(customer);
 
	}
 
	@RequestMapping(value = "/addCustomer", method = RequestMethod.PUT, headers = "Accept=application/json")
	public Customer updateCustomer(@RequestBody Customer customer) {
		return customerService.updateCustomer(customer); 
 
	}	
 
	@RequestMapping(value = "/deleteCustomer/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
	public void deleteCustomer(@PathVariable("id") int id) {
		customerService.deleteCustomer(id);
 
 
	}	
}

服务层

第7步:在Package .org.igi.theitroad.service中创建名为"customereservice.java"的文件

package org.igi.theitroad.service;
 
import java.util.List;
 
import javax.transaction.Transactional;
 
import org.igi.theitroad.dao.CustomerDao;
import org.igi.theitroad.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
 
@Service("customerService")
public class CustomerService {
 
	@Autowired
	CustomerDao customerDao;
 
	@Transactional
	public List<Customer> getAllCustomers() {
		return customerDao.getAllCustomers();
	}
 
	@Transactional
	public Customer getCustomer(int id) {
		return customerDao.getCustomer(id);
	}
 
	@Transactional
	public Customer addCustomer(Customer customer) {
		customerDao.addCustomer(customer);
		return customer;
	}
 
	@Transactional
	public Customer updateCustomer(Customer customer) {
		customerDao.updateCustomer(customer);
		return customer;
	}
 
	@Transactional
	public void deleteCustomer(int id) {
		customerDao.deleteCustomer(id);
	}
}

DAO层

第8步:在Package .org.igi.theitroad.dao中创建名为"customerdao.java"的接口

package org.igi.theitroad.dao;
 
import java.util.List;
 
import org.igi.theitroad.springboot.Customer;
 
public interface CustomerDao {
	public List<Customer> getAllCustomers() ;
 
	public Customer getCustomer(int id) ;
 
	public Customer addCustomer(Customer customer);
 
	public void updateCustomer(Customer customer) ;
 
	public void deleteCustomer(int id) ;
}

步骤9:在包中创建名为"customerdaoimpl.java"的文件.igi.theitroad.dao

package org.igi.theitroad.dao;
 
import java.util.List;
 
import org.igi.theitroad.model.Customer;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository
public class CustomerDaoImpl implements CustomerDao{
 
	@Autowired
	private SessionFactory sessionFactory;
 
	public void setSessionFactory(SessionFactory sf) {
		this.sessionFactory = sf;
	}
 
	public List<Customer> getAllCustomers() {
		Session session = this.sessionFactory.getCurrentSession();
		List<Customer>  customerList = session.createQuery("from Customer").list();
		return customerList;
	}
 
	public Customer getCustomer(int id) {
		Session session = this.sessionFactory.getCurrentSession();
		Customer customer = (Customer) session.get(Customer.class, id);
		return customer;
	}
 
	public Customer addCustomer(Customer customer) {
		Session session = this.sessionFactory.getCurrentSession();
		session.save(customer);
		return customer;
	}
 
	public void updateCustomer(Customer customer) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(customer);
	}
 
	public void deleteCustomer(int id) {
		Session session = this.sessionFactory.getCurrentSession();
		Customer p = (Customer) session.load(Customer.class, new Integer(id));
		if (null != p) {
			session.delete(p);
		}
	} 
}

AngularJS View.

步骤10:在包中创建名为"customerDataAngularjs.html"的文件.src.main.webapp

<html>
<head>
<script
	src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
 
<title>Spring Boot AngularJS example</title>
<script type="text/javascript">
            var app = angular.module("CustomerManagement", []);
         
            //Controller Part
            app.controller("CustomerController", function($scope, $http) {
         
               
                $scope.customers = [];
                $scope.customerForm = {
                    id : -1,
                    customerName : "",
                    email : ""
                };
         
                //Now load the data from server
                _refreshCustomerData();
         
                //HTTP POST/PUT methods for add/edit customer 
                //with the help of id, we are going to find out whether it is put or post operation
                
                $scope.submitCustomer = function() {
         
                    var method = "";
                    var url = "";
                    if ($scope.customerForm.id == -1) {
                        //Id is absent in form data, it is create new customer operation
                        method = "POST";
                        url = '/addCustomer';
                    } else {
                        //Id is present in form data, it is edit customer operation
                        method = "PUT";
                        url = '/addCustomer';
                    }
         
                    $http({
                        method : method,
                        url : url,
                        data : angular.toJson($scope.customerForm),
                        headers : {
                            'Content-Type' : 'application/json'
                        }
                    }).then( _success, _error );
                };
         
                //HTTP DELETE- delete customer by Id
                $scope.deleteCustomer = function(customer) {
                    $http({
                        method : 'DELETE',
                        url : '/deleteCustomer/' + customer.id
                    }).then(_success, _error);
                };
 
             //In case of edit, populate form fields and assign form.id with customer id
                $scope.editCustomer = function(customer) {
                  
                    $scope.customerForm.customerName = customer.customerName;
                    $scope.customerForm.email = customer.email;
                    $scope.customerForm.id = customer.id;
                };
         
                /* Private Methods */
                //HTTP GET- get all customers collection
                function _refreshCustomerData() {
                    $http({
                        method : 'GET',
                        url : 'http://localhost:8080/getAllCustomers'
                    }).then(function successCallback(response) {
                        $scope.customers = response.data;
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
                }
         
                function _success(response) {
                    _refreshCustomerData();
                    _clearFormData()
                }
         
                function _error(response) {
                    console.log(response.statusText);
                }
         
                //Clear the form
                function _clearFormData() {
                    $scope.customerForm.id = -1;
                    $scope.customerForm.customerName = "";
                    $scope.customerForm.email = "";
                
                };
            });
        </script>
<style>
.blue-button {
	background: #25A6E1;
	filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',
		endColorstr='#188BC0', GradientType=0);
	padding: 3px 5px;
	color: #fff;
	font-family: 'Helvetica Neue', sans-serif;
	font-size: 12px;
	border-radius: 2px;
	-moz-border-radius: 2px;
	-webkit-border-radius: 4px;
	border: 1px solid #1A87B9
}
 
.red-button {
	background: #CD5C5C;
	padding: 3px 5px;
	color: #fff;
	font-family: 'Helvetica Neue', sans-serif;
	font-size: 12px;
	border-radius: 2px;
	-moz-border-radius: 2px;
	-webkit-border-radius: 4px;
	border: 1px solid #CD5C5C
}
 
table {
	font-family: "Helvetica Neue", Helvetica, sans-serif;
	width: 50%;
}
 
caption {
	text-align: left;
	color: silver;
	font-weight: bold;
	text-transform: uppercase;
	padding: 5px;
}
 
th {
	background: SteelBlue;
	color: white;
}
 
tbody tr:nth-child(even) {
	background: WhiteSmoke;
}
 
tbody tr td:nth-child(2) {
	text-align: center;
}
 
tbody tr td:nth-child(3), tbody tr td:nth-child(4) {
	text-align: center;
	font-family: monospace;
}
 
tfoot {
	background: SeaGreen;
	color: white;
	text-align: right;
}
 
tfoot tr th:last-child {
	font-family: monospace;
}
 
td, th {
	border: 1px solid gray;
	width: 25%;
	text-align: left;
	padding: 5px 10px;
}
</style>
<head>
<body ng-app="CustomerManagement" ng-controller="CustomerController">
	<h1>Customer Mart</h1>
	<form ng-submit="submitCustomer()">
		<table>
 
			<tr>
				<th colspan="2">Add/Edit customer</th>
			</tr>
			<tr>
				<td>Customer Name</td>
				<td><input type="text" ng-model="customerForm.customerName" </td>
			</tr>
			<tr>
				<td>Email</td>
				<td><input type="text" ng-model="customerForm.email" </td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Submit"
					class="blue-button" </td>
			</tr>
		</table>
	</form>
	<table>
		<tr>
 
			<th>Customer Name</th>
			<th>Email</th>
			<th>Operations</th>
 
		</tr>
 
		<tr ng-repeat="customer in customers">
 
			<td>{{ customer.customerName }}</td>
			<td>{{ customer.email }}</td>
 
			<td><a ng-click="editCustomer(customer)" class="blue-button">Edit</a>
				| <a ng-click="deleteCustomer(customer)" class="red-button">Delete</a></td>
		</tr>
 
	</table>
</body>
</html>

解释 :

  • 我们已经注入$HTTP,因为我们通过控制器构造函数在Ajax示例中完成了$HTTP。
app.controller("CustomerController", function($scope, $http) {
         
               
                $scope.customers = [];
...
  • 我们已经定义了各种方法,具体取决于EditCustomer,Deletecustomer,SubmitCustomer等操作
  • 单击表单上的"提交"按钮时,它实际上会根据操作调用帖子或者放置。如果我们单击"编辑"并提交数据,那么它将被按照现有资源更新。如果直接提交数据,那么它将是创建新资源的发布操作,
  • 每次提交数据时,它都会调用引用COSTOMERDATA()来刷新下面的客户表。
  • 当我们调用$HTTP时,我们需要通过方法类型和URL,它将根据Web应用程序的上下文根目录放置绝对URL或者相对URL。
//HTTP GET- get all customers collection
                function _refreshCustomerData() {
                    $http({
                        method : 'GET',
                        url : 'http://localhost:8080/getAllCustomers'
                    }).then(function successCallback(response) {
                        $scope.customers = response.data;
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
                }
                }

Spring boot 主文件

步骤11:在Package .org.igi.theitroad中创建名为"springboottangularjsapplication.java"的文件

package org.igi.theitroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class SpringBootAngularJSApplication {
 
	public static void main(String[] args) 
	{
		SpringApplication.run(SpringBootAngularJSApplication.class, args);   
	}
}

我们刚刚添加了@springbootapplication,它做了所有的工作。
让我们了解更多关于这个注释的信息。
@springBootApplication是添加以下所有内容的注释:

@configuration使类作为应用程序上下文的Bean定义的源。
@EnableAutoConfiguration允许Spring Boot在ClassPath设置和各种属性设置中添加Bean礼物。
通常,我们将为Spring MVC应用程序添加@bableWebMVC,但Spring Boot会在类路径上看到Spring-WebMVC时自动添加它。
将应用程序标记为Web应用程序,并激活诸如设置DispatcherServlet之类的关键行为。
@ComponentsCan告诉Spring在默认包中查找其他组件,配置和服务,允许它找到控制器。
如果未定义特定包,则会从声明此注释的类的包中扫描。

运行应用程序

第12步:是时候制造了maven的时候了。

右键单击项目 - >运行AS - > Maven Build

步骤13:提供单击清洁安装的目标:运行(下面给出)并单击"运行"

步骤14:使用Maven Build完成后,让我们转到浏览器并置于URL之后。

http://localhost:8080/customerdataangularjs.html

添加以下详细信息到客户名称:作为"John"和电子邮件作为"[email protected]",然后单击提交。

现在我正在使用上述方法添加更多客户。

让我们单击与客户ID对应的编辑链接:3,其中名称为David。

我正在更改"[email protected]"的电子邮件地址到"[email protected]"

单击"提交"时,我们将看到以下屏幕。

正如我们可以看到David的电子邮件地址已更改为"更改@ gmail.com"。

让我们点击与客户ID相对应的删除链接:2姓名是Martin,我们将看到下面的屏幕。

正如我们所看到的,Martin已从列表中删除。