Connecting Angular 4 Application to Java EE Application

In this article, we will learn how Angular 4 application connects to JAVA EE application(its backend) and fetches data from backend and displays them in Angular UI.

Here we will be using two separate applications, one for JAVA EE and another for Angular 4 front end, Though we can create both applications under the single project.

Developing JAVA EE application

Though we can use any eclipse here IDE is luna eclipse IDE(4.4.2). Please find below project structure(created in Eclipse).

We will discuss technologies used in more detail one by one.

Our Java EE application uses an embedded Derby database and EclipseLink as a provider with JPA. We are
initially creating SCHEMA named as ‘PERSONDB’ with few some data that application can show sample data.

REST web service design:
JAVA EE application will expose REST web service using Jersey client(2.0 version). we use Jersey(2.0) client for
REST->Mainly Jersey RESTful Web Services framework is an open source framework for developing RESTful Web
Services in Java. It provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference

Jersey and supporting libraries can be imported like below select Project >Configure Facets… > Install JAX-RS Facet and proceed to select version 2.0 of JAX-RS.
Alternatively, if you are using MAVEN, then all supporting dependencies have to be put in pom.xml file like

Configuration file

On the server side, Jersey provides a servlet implementation which scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web application. We also define context root path that will be used in REST URL.
In our case, Rest URL pattern will contain ‘/jaxrs/rest/v1.1/*’.

JPA Classes
In our case, We create and use schema “PERSONDB” and with the single table named “PERSON” table. For this table, we
create JPA entity Person using JPA annotation.

package com.dunebook.webclipse.example;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
 * Person entity. @author vikas 
@Table(name = "PERSON", schema = "PERSONDB")
public class Person implements {
    // Fields
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private String gender;
    private String city;
    // Constructors
    /** default constructor */
    public Person() {

    public Person(Integer id) { = id;

    public Person(Integer id, String name,
            String gender, String city) { = id; = name;
        this.gender = gender; = city;
    // Property accessors
    @Column(name = "ID")
    public Integer getId() {

    public void setId(Integer id) { = id;

    @Column(name = "NAME", length = 50)
    public String getName() {

    public void setName(String name) { = name;

    @Column(name = "GENDER", length = 20)
    public String getGender() {
        return this.gender;
    public void setGender(String gender) {
        this.gender = gender;

    @Column(name = "CITY", length = 30)
    public String getCity() {
        return city;
    public void setCity(String city) { = city;
    }   }

Rest web service
This class exposes REST services via JAX-RS.

Recommended :  Webstorm vs Angular IDE for Angular coding

import java.util.List;
import javax.persistence.EntityManager;
import com.dunebook.webclipse.example.EntityManagerHelper;
import com.dunebook.webclipse.example.Person;
 * @author vikas
public class PersonFacadeREST extends AbstractFacade {
    private EntityManager em;
    public PersonFacadeREST() {
    @Consumes({ "application/xml", "application/json" })
    public Response edit(Person entity) {
        if (entity.getName().length() <= 3) {
            return Response.status(Status.CONFLICT).entity("Customer name is too short").type(MediaType.TEXT_PLAIN).build();
        return super.edit(entity);
    public Response remove(@PathParam("id") Integer id) {
        return super.remove(super.find(id));
    @Produces({ "application/json" })
    public Person find(@PathParam("id") Integer id) {
        return super.find(id);

    @Produces({ "application/json" })
    public List findAll() {
        return super.findAll();

    @Produces({ "application/xml", "application/json" })
    public List findRange(@PathParam("from") Integer from,
            @PathParam("to") Integer to) {
        return super.findRange(new int[] { from, to });

    public String countREST() {
        return String.valueOf(super.count());

    protected EntityManager getEntityManager() {
        em = EntityManagerHelper.getEntityManager();
        return em;

A few key annotations and methods:

public class PersonFacadeREST
Our person services will be available at the JAX-RS service relative path, Person – i.e.,
/jaxrs/rest/v1.1/*/Person relative to our application’s webroot.

 @Produces({ "application/json" })
 public List findAll() {
 return super.findAll();

If a call is made to /jaxrs/rest/v1.1/*/Person with the HTTP GET method, a list of all people is returned. The
@Produces annotation tells JAX-RS that this method can produce JSON output.

 @Produces({ "application/xml", "application/json" })
 public Person find(@PathParam("id") Integer id) {
 return super.find(id);

At /jaxrs/rest/v1.1//Person/{id} (/jaxrs/rest/v1.1//Person/2 for example) you will get Person object
containing the details of the person with the specified Id.

Developing Angular 4 Application

Now we are going to develop Angular 4 application. here we will explain how to create component, services
, interfaces and run them.

IDE: Angular IDE by Webclipse.

Note – RxJS: Angular 4 will use this to communicate REST service exposed by JAVA EE application.

Create the Project
The first step is to create a new Angular 4 project using the New Angular 4 Project wizard. To get started,
select File > New > Angular Project. Type in a name for the project, and then click “Finish” to accept
the default settings.

Create the Person Interface
To create interface, use project wizard and select New > Interface. Note that we’ve added a person segment to the path so that we can
group all the functionality in this single folder.

In our Person interface, we simply define different attributes of the Person we will be displaying and

Replace the code generated in person.ts with the following:
Person.ts source

export interface Person {
  id: number;
  name: string;
  gender: string;
  city: string

Create the Person Service
To create the service, select New > Service. Be sure to expand the Advanced group and select “Do not create
the code in its own directory” so that we don’t get another subfolder.

Recommended :  Create a kanban board with Angular 4

Use project wizard to create service

The Person service is only responsible for hitting REST services exposed by JAVA EE application. this service will perform read/write operation to our database.

Replace the code generated in person.service.ts with the following:

Person.service.ts source:

import { Injectable } from [email protected]/core';
import { Http, Response, Headers } from [email protected]/http';
import { Observable } from 'rxjs/Observable';
import { Person } from './person';
import 'rxjs/add/operator/map';

export class PersonService {

  private baseUrl = 'http://localhost:8080/SWBackend/jaxrs/rest/v1.1/';

  constructor(private http: Http) {

get(id: number): Observable {
    const person$ = this.http
      .get(`${this.baseUrl}/Person/${id}`, {headers: this.getHeaders()})
      return person$;

  getAll(): Observable {
     const person$ = this.http
      .get(`${this.baseUrl}/Person`, {headers: this.getHeaders()})
    return person$;
   private getHeaders() {
    const headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/json');
    return headers;
function mapPersons(response: Response): Person[] {
  return response.json().map(toPerson);
function mapPerson(response: Response): Person {
  return toPerson(response.json());
function toPerson(r: any): Person {
  return r;

Some important key REST method:

get method Used to get the details of a single Person.
getAll method Used to get a list of Persons.
both methods make HTTP call to REST service exposed by JAVA EE application.
toPerson method Used to make the conversion of the received JSON to our local Person interface.

Finally, we have to register our service as a provider in the app module – app.module.ts.
We need to import the service class and list it in the providers array. Please find same below in providers

Creating Components

Now We’re going to display a list of people, For that, we create Person list component like below
Angular components.
Create the Person List Component
From the app/person context menu, choose New > Component. Again, uncheck the “Do not create the code in its own directory” option (do this for each component you create).

The component is automatically imported and declared in the app module, app.module.ts, so you don’t have to do
this yourself.
On clicking finish, we will get the Personlist.component.ts class and the personlist.component.html template class. Replace the generated code with the code below.

Personlist.component.html source:

 <div class="personlistcss">
<section *ngIf="people" class = "panel-body">
    <table class = "table-striped table-bordered table-hover table-condensed">
        <tr *ngFor="let person of people">
            <td><a href="#" [routerLink]="['/person',]">
                    {{}} </a>  </td>

Create the Person Details Component

import { Component, OnInit } from [email protected]/core';
import { ActivatedRoute, Router } from [email protected]/router';
import { Person } from './person';
import { PersonService } from './person.service';
  selector: 'app-persondetail',
  templateUrl: './persondetail.component.html',
  styleUrls: ['./persondetail.component.css']
export class PersondetailComponent implements OnInit {
  person: Person;
  sub: any;
  constructor(private personService: PersonService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      const id = Number.parseInt(params['id']);
      this.personService.get(id).subscribe(p => this.person = p);



< div align="center">
  Person Detail information!
<section *ngIf="person" class = "panel">
< div class="input-group">

            <input type="text" class = "form-control textCss" [(ngModel)]="">
            <input type="text" class = "form-control textCss" [(ngModel)]="">
            <input type="text" class = "form-control textCss" [(ngModel)]="person.gender">
            <input type="text" class = "form-control textCss" [(ngModel)]="">

        < /div>
< /section>

Setting up Routes

So we’ve created a number of components, Now we have to wire them so that they can work together . Please see app.modules.ts file where in we define all route.

import { BrowserModule } from [email protected]/platform-browser';
import { NgModule } from [email protected]/core';

import { AppComponent } from './app.component';
import { HttpModule } from [email protected]/http';
import { FormsModule } from [email protected]/forms';
import { RouterModule, Routes } from [email protected]/router';
import { PersonService } from './person/person.service';
import { PersonlistComponent } from './person/personlist.component';
import { PersondetailComponent } from './person/persondetail.component';

const appRoutes: Routes = [
// map '/persons' to the people list component
  { path: 'people', component: PersonlistComponent },

 // map '/persons/:id' to person details component
  { path: 'person/:id', component: PersondetailComponent },

// map '/' to '/persons' as our default route
  { path: '', redirectTo: '/people',pathMatch: 'full' },

  declarations: [
  imports: [
  providers: [PersonService],
  bootstrap: [AppComponent]
export class AppModule { }

Running Your Application

Deploy the back-end application
Since we have two different application and Angular 4 fetches data from JAVA EE application so Please make sure
that JAVA EE backend application should start running first. You can now deploy your
application using Run As > Run on Server Application to deploy the back end to your preferred Java EE
To verify whether service is running perfectly:
Use google postman agent as client to test rest web service URL
http://localhost:8080/SWBackend/jaxrs/rest/v1.1//Person like below. It returns response in json format.

Recommended :  learn how to create seeds in laravel

Deploy the front-end application
Now this is the time to deploy your application from the project’s context menu, choose Run As > Angular
Web Application or you can even start the application from the Servers view – FirstAngular4 will be listed
under the Angular CLI node. Again, in the Terminal+ view, you should see the output of the “ng serve” process
that is deploying your application.

if you used the Run As action, chrome will automatically open with the deployed application – if not, open a
browser and navigate to http://localhost:4200/ to see the front end in action.

Finally our application is running

Angular 4 UI(list of Person)

On clicking on any of Person listed, it will display detail of that particular Person

About the author

vikas gupta

Passionate about learning new technologies . Having 7yrs of Hands on experience on JAVA/J2EE application in various multinational product based company.
Have 2 yrs of live experience of JAVA trainer to train professionals.

  • jesus armando macias benitez

    wich IDE do you use for angular ?

Pin It on Pinterest