# Getting Started with Kendo UI for Angular in a Java Spring Application

This Article provides a step-by-step guide that uses the [Spring Initializr](https://start.spring.io/) to create a new Java Spring Boot application and integrate the [Kendo UI for Angular component library](https://www.telerik.com/kendo-angular-ui/components/).

> Want to jump straight to the runnable application? Check out the [Kendo UI for Angular Data Grid and Upload Integration with Java Spring Boot](https://github.com/telerik/kendo-angular/tree/master/examples-standalone/kendoangular-java-integration) application and follow the steps in the `README`.

## Prerequisites

Before proceeding, ensure that you have the following installed:

* [System Requirements For Kendo UI for Angular](https://www.telerik.com/kendo-angular-ui-develop/components/installation/requirements/)

* [Node.js 20](https://nodejs.org/en/download/)

* [Angular 18 CLI](https://angular.dev/installation#install-angular-cli)

* [Java 23](https://www.oracle.com/java/technologies/downloads/)
  * Note: For macOS, ensure you download the correct installer for your architecture:
    * **arm64**: For Apple Silicon (M1, M2, etc.) Macs.
    * **x64**: For Intel-based Macs.

* [Apache Maven 3.9.9](https://maven.apache.org/install.html)
  * For Mac users, you can install Maven using [Homebrew](https://brew.sh/):

    ```bash
    brew install maven@3.9.9
    ```

* [Visual Studio Code](https://code.visualstudio.com/download) with [Java extensions](https://code.visualstudio.com/docs/java/extensions) or another code editors like [Eclipse](https://www.eclipse.org/) and [IntelliJ](https://www.jetbrains.com/idea/download/).

The versions listed above are current as of October 07, 2024.

## Create a New Java Spring Boot Application

To create a new Java Spring Boot application:

1. Open the [Spring Initializr](https://start.spring.io/) in your browser.

2. Choose your settings and dependencies. For this guide, use the following settings:
   * **Project**: Maven Project
   * **Language**: Java
   * **Spring Boot**: 3.3.4
   * **Project Metadata**:
     * **Group**: com.example
     * **Artifact**: kendo-angular-java
     * **Name**: kendo-angular-java
     * **Description**: Kendo UI for Angular with Java Spring Boot Integration
     * **Package Name**: com.example.kendo-angular-java
     * **Packaging**: Jar
     * **Java**: 23
   * **Dependencies**: Add the following dependencies:
     * **Spring Web**
     * **Spring Boot DevTools**
     * **Spring Data JPA**
     * **H2 Database**

3. Click the **Generate** button to download the project.

4. Create a new folder that will contain both the backend and frontend applications. For example, create a folder named `kendo-angular-java`.

5. Extract the downloaded project into the `kendo-angular-java` folder.

6. Run the application using the following command:

   ```bash
   mvn spring-boot:run
   ```

7. Open your browser and navigate to `http://localhost:8080`. You should see the default Spring Boot application page.

## Integrate Kendo UI for Angular

1. In the main folder, create a new folder named `ClientApp` to store the Angular application.

   * Your structure should look like this:

   ```plaintext
   kendo-angular-java (root)
   ├── backend (Spring Boot application)
   ├── ClientApp (Angular application)
   ```

2. Navigate to the `ClientApp` folder in the project.

   ```bash
   cd ClientApp
   ```

3. [Install the Kendo UI for Angular Data Grid](https://www.telerik.com/kendo-angular-ui-develop/components/grid/installation/getting-started#installing-the-component) by running the following command:

   ```bash
   ng add @progress/kendo-angular-grid
   ```

4. Add the Kendo UI for Angular Data Grid [standalone directive](https://www.telerik.com/kendo-angular-ui-develop/components/grid/installation/dependecies-and-utils) to your component:

   ```ts
   import { KENDO_GRID } from '@progress/kendo-angular-grid';

   @Component({
       selector: 'app-root',
       standalone: true,
       imports: [KENDO_GRID],
       templateUrl: './app.component.html',
       styleUrl: './app.component.css',
   })
   ```

5. Add a Kendo UI for Angular Grid component to the `home.component.html` file:

   ```html
   <kendo-grid
       [data]="gridData"
       [pageable]="true"
       [pageSize]="state.take"
       [skip]="state.skip"
       [sortable]="true"
       [sort]="state.sort"
       [groupable]="true"
       [group]="state.group"
       [filterable]="true"
       [filter]="state.filter"
       (dataStateChange)="dataStateChange($event)"
   >
       <kendo-grid-column field="productID" title="Product ID">
       </kendo-grid-column>
       <kendo-grid-column field="productName" title="Product Name">
       </kendo-grid-column>
       <kendo-grid-column field="unitPrice" title="Unit Price">
       </kendo-grid-column>
   </kendo-grid>
   ```

6. Create a `Product` class in the `Models` folder:

   ```java
   public class Product {
       private int productID;
       private String productName;
       private double unitPrice;

       public Product() {
       }

       public Product(int productID, String productName, double unitPrice) {
           this.productID = productID;
           this.productName = productName;
           this.unitPrice = unitPrice;
       }

       public int getProductID() {
           return productID;
       }

       public void setProductID(int productID) {
           this.productID = productID;
       }

       public String getProductName() {
           return productName;
       }

       public void setProductName(String productName) {
           this.productName = productName;
       }

       public double getUnitPrice() {
           return unitPrice;
       }

       public void setUnitPrice(double unitPrice) {
           this.unitPrice = unitPrice;
       }

       @Override
       public String toString() {
           return "Product{" +
                   "productID=" + productID +
                   ", productName='" + productName + '\'' +
                   ", unitPrice=" + unitPrice +
                   '}';
       }
   }
   ```

   If the `Models` folder does not exist, create it in the `src/main/java/**group placeholder**/**artifact placeholder**/` folder.

7. Create a Java Spring Boot controller to fetch the data. For simplicity, in this guide, the data is hardcoded in the controller:

   ```java
   @RestController
   @RequestMapping("/products")
   public class ProductController {

       private static List<Product> products = new ArrayList<>();

       static {
           products.add(new Product(1, "Chai", 18));
           products.add(new Product(2, "Chang", 19));
           products.add(new Product(3, "Aniseed Syrup", 10));
           products.add(new Product(4, "Chef Anton's Cajun Seasoning", 22));
           products.add(new Product(5, "Chef Anton's Gumbo Mix", 21.35));
           products.add(new Product(6, "Grandma's Boysenberry Spread", 25));
           products.add(new Product(7, "Uncle Bob's Organic Dried Pears", 30));
           products.add(new Product(8, "Northwoods Cranberry Sauce", 40));
           products.add(new Product(9, "Mishi Kobe Niku", 97));
           products.add(new Product(10, "Ikura", 31));
           products.add(new Product(11, "Queso Cabrales", 21));
           products.add(new Product(12, "Queso Manchego La Pastora", 38));
       }

       @PostMapping("/get-products")
       public DataSourceResult getProducts(@RequestBody DataSourceRequest request) {
           return QueryableExtensions.toDataSourceResult(products, request);
       }
   }
   ```

   Import `DataSourceRequest`, `DataSourceResult`, and `QueryableExtensions` from the custom [`telerik.demo.datasource`](https://github.com/telerik/kendo-angular/tree/master/examples-standalone/kendoangular-java-integration/backend/src/main/java/telerik/demo/datasource) package in the runnable example.

8. Create an Angular service to fetch the data from the Java controller, and then update the `services/product.service.ts` file:

   ```bash
   ng generate service services/product
   ```

   ```ts
   import { Injectable } from '@angular/core';
   import { HttpClient } from '@angular/common/http';
   import { map, Observable } from 'rxjs';
   import { State, translateDataSourceResultGroups } from '@progress/kendo-data-query';
   import { GridDataResult } from '@progress/kendo-angular-grid';


   @Injectable({
       providedIn: 'root'
   })
   export class ProductService {
       private baseUrl = 'http://localhost:8080/';

       constructor(private http: HttpClient) {}

       public getProducts(state: State): Observable<GridDataResult> {
           const url = `${this.baseUrl}products/get-products`;
           const hasGroups = state.group && state.group.length;

           return this.http.post<GridDataResult>(url, state).pipe(
               map((response) => ({
                   data: hasGroups ? translateDataSourceResultGroups(response.data) : response.data,
                   total: response.total,
                   aggregates: response.aggregates
               }))
           );
       }
   }
   ```

   The service posts the current Grid state to the Java controller. The controller applies the requested operations and returns the processed data and total count.

9. Update the `home.component.ts` file to fetch the data from the service:

   ```ts
   import { Component } from '@angular/core';
   import { DataStateChangeEvent, GridDataResult } from '@progress/kendo-angular-grid';
   import { ProductService } from './products.service';

   @Component({
       selector: 'app-home',
       templateUrl: './home.component.html',
   })
   export class HomeComponent {
       public state: State = { skip: 0, take: 5, filter: { filters: [], logic: 'or' }, group: [], sort: [] };
       public gridData: GridDataResult = { data: [], total: 0 };
       public productService = inject(ProductService);

       ngOnInit(): void {
           this.getProducts(this.state);
       }

       public dataStateChange(state: DataStateChangeEvent): void {
           this.state = state;
           this.getProducts(state);
       }

       private getProducts(state: State): void {
           this.productService.getProducts(state).subscribe({
               next: (result) => { this.gridData = result; },
               error: (error) => console.error(error),
           });
       }
   }
   ```

10. Run both the Java Spring Boot application and the Angular application:

    ```bash
    mvn spring-boot:run
    ```

    ```bash
    ng serve
    ```

11. Open your browser and navigate to `http://localhost:4200`.

The application will now display the Kendo UI for Angular Data Grid with the data fetched from the Java Spring controller.

## Perform Data Operations and Handle File Uploads

Most applications that use the Kendo UI for Angular Grid require you to manage the data state and perform CRUD operations. Handling file uploads is also a common requirement, where the Kendo UI for Angular Upload component in conjunction with Java Spring Boot comes in handy.

This part of the article guides you through the configuration of the data operations and the Upload component by providing references to the relevant resources, without covering every step of the process.

### Handling Grid Data Operations

There are several ways to handle data operations with the Kendo UI for Angular Grid. The two most common are:

* Client-side Operations: You can use the [`process`](https://www.telerik.com/kendo-angular-ui-develop/components/data-query/api/process) method to handle data operations like sorting, filtering, and paging on the client. For more information, refer to the [Data Operations](https://www.telerik.com/kendo-angular-ui-develop/components/grid/data-operations) article.

* Server-side Operations: Handle the Grid state on the server by implementing the required data operations. This article demonstrates a custom `POST /products/get-products` endpoint that accepts `DataSourceRequest` and returns a processed `DataSourceResult`. Its [backend data-source implementation](https://github.com/telerik/kendo-angular/tree/master/examples-standalone/kendoangular-java-integration/backend/src/main/java/telerik/demo/datasource) applies filtering, sorting, paging, grouping, and aggregates.

### Handling Data Grid CRUD Operations

[CRUD](https://developer.mozilla.org/en-US/docs/Glossary/CRUD) operations can be handled by using the [`add`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#add), [`edit`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#edit), [`save`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#save) ,[`cancel`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#cancel), and [`remove`](https://www.telerik.com/kendo-angular-ui-develop/components/grid/api/gridcomponent#remove) events. For more information, refer to the [Editing Basics](https://www.telerik.com/kendo-angular-ui-develop/components/grid/editing/basics) article. On the server side, you need to handle the `Post`, `Put`, `Get`, and `Delete` requests to handle the CRUD operations.

The following application demonstrates how to handle data and CRUD operations with the Kendo UI for Angular Data Grid and Java Spring Boot:

[Kendo UI for Angular Data Grid and Upload Integration with Java Spring](https://github.com/telerik/kendo-angular/tree/master/examples-standalone/kendoangular-java-integration)

The application uses static data, but in a real-world scenario, you need to replace the static data with data from a database. Spring Data JPA can be used to handle the database operations. For more information, refer to the [Spring Data JPA](https://spring.io/projects/spring-data-jpa) documentation.

### Handling Files Using Upload Component

On the client side, add the [`saveUrl`](https://www.telerik.com/kendo-angular-ui-develop/components/uploads/api/uploadcomponent#saveurl) and [`removeUrl`](https://www.telerik.com/kendo-angular-ui-develop/components/uploads/api/uploadcomponent#removeurl) properties to the Upload component to handle the file upload and remove operations. The `saveUrl` and `removeUrl` properties must point to the server-side methods that handle the file upload and remove operations.

On the server side, handle the uploaded files by using the [`MultipartFile`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html) interface. For more information, refer to the [Upload files in Java Spring Boot](https://spring.io/guides/gs/uploading-files/) article. Here is an example method to handle file uploads:

```java
@PostMapping("/upload")
public ResponseEntity<String> onPostUpload(@RequestParam("files") List<MultipartFile> files) {
    // Handle the file upload.
    return "File uploaded successfully";
}
```

The [Kendo UI for Angular Grid and Upload Integration with Java Spring](https://github.com/telerik/kendo-angular/tree/master/examples-standalone/kendoangular-java-integration) application demonstrates how to handle file uploads with the Kendo UI for Angular Upload component and Java Spring Boot.

## Suggested Links

* [Kendo UI for Angular with ASP.NET Core Integration](https://www.telerik.com/kendo-angular-ui-develop/components/installation/dotnet-core)
* [Getting Started with Kendo UI for Angular](https://www.telerik.com/kendo-angular-ui-develop/components/getting-started)
* [Kendo UI for Angular Components](https://www.telerik.com/kendo-angular-ui)
* [Kendo UI for Angular Documentation](https://www.telerik.com/kendo-angular-ui/components/)
* [Kendo UI for Angular Data Grid Component](https://www.telerik.com/kendo-angular-ui-develop/components/grid)
* [Kendo UI for Angular Upload Component](https://www.telerik.com/kendo-angular-ui-develop/components/uploads/upload)
* [All Things Angular Telerik Blog Page](https://www.telerik.com/blogs/all-things-angular)
